Trigger a JavaScript alert message upon clicking the close button

I have encountered an issue with my current code. When I click on the close (X) button, it should display an error message stored in variable s. Previously, the script was functioning correctly but now it is not showing any alerts when I click on the close button. Could there be a mistake in my coding or do I need to add a .js file for this functionality to work?

var internalLink = false;

function pageUnload() {
    if (!internalLink && location.protocol != 'http:') {
        internalLink = true;
        var s = 'Alert Message';
        if (navigator.userAgent.indexOf("Firefox") > -1) {
            alert(s);
        }
        setTimeout("location.href= 'foo.com'", 100);
        return s;
    }
}
window.onbeforeunload = pageUnload;

Alternatively, could you share some other code with me that will trigger an alert stored in variable s when the user clicks on the close button? Please note that the alert should only be displayed when the close button is clicked, not when redirecting to another link or submitting a form. No alert should appear when clicking on internal links.

Answer №1

There are limitations to what the onbeforeunload event can do in different browsers. Some browsers may not even support it, like Opera for example.

This event is primarily used to display a confirmation box asking if the user wants to leave the page or not. It cannot execute functions like alert or confirm, redirect the user, make AJAX calls, or perform other actions.

Instead, you can only return a string that will be displayed in a browser-generated alert confirming whether the user wants to leave or stay. Note that Firefox may not always show this string (bug# 588292).

var internalLink = false;

function pageUnload() {
    if (!internalLink && location.protocol != 'http:') {
        internalLink = true;
        var s = 'Alert Message';
        
        // You are limited in what you can do here
        
        return s; // This message will appear in a confirm popup
    }
}
window.onbeforeunload = pageUnload;

Browsers handle and trigger onbeforeunload in specific ways, so caution should be exercised when using this event.

There is no definitive method to determine whether the user clicked "leave" or "stay". The common approach involves using the unload event along with a setTimeout, although it is considered hacky.

var internalLink = false,
    stayTimeout, stayClicked;

function pageUnload() {
    if(stayClicked){
        return; // Prevent running multiple times
    }

    if (!internalLink && location.protocol != 'http:') {
        internalLink = true;
        stayClicked = true; // Mark event as executed once

        setTimeout(stayOnPage, 1000);

        var s = 'Alert Message';

        return s; // This message will appear in a confirm popup
    }
}

function stayOnPage(){
    location.href= 'foo.com'; // Redirect if user chooses to stay

    // Reset stayClicked if not redirecting
    // stayClicked = false;
}
function leavePage(){
    clearTimeout(stayTimeout); // Clear timeout on page leave
}

window.onbeforeunload = pageUnload;
window.unload = leavePage;

A better alternative is to attach events to <a> tags, use custom confirm boxes, and proceed accordingly.

var a = document.getElementsByTagName('a');
for(var b in a){
    a[b].addEventListener('click', function(e){
        var c = confirm('Do you want to follow this link?');

        if(c){
            return true; // Allow user to leave
        }
        else{
            e.preventDefault(); // Block link click
            location.href= 'foo.com'; // Redirect if needed
        }
    });
}

Answer №2

You are facing multiple issues in your code

1) Instead of passing a string to setTimeout, you should pass a function

Incorrect:

setTimeout("location.href= 'foo.com'", 100);

Correct:

setTimeout(function(){location.href= 'foo.com'}, 100);

2) According to the HTML5 spec, alert calls may be ignored during the onbeforeunload event (as observed in Firefox).

3) Redirection is not permitted in the unload event either.

You can only return a string that prompts the user if they want to leave the page. While the event is cancelable, redirecting within the event itself is not allowed.

https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

InvalidSelectorError: The specified selector is not valid //button[contains(., 'buttonText')] while running JavaScript code

Here's an example of HTML code that I am working with: <button id="toolbar-item-17-update-id" type="submit" name="action" value="update" class="button-action-update btn btn-secondary"> Ed ...

Unusual occurrences when making several ajax requests to a single URL

I've encountered a peculiar scenario while working on a CherryPy server, and I'm seeking assistance in understanding the intricacies behind it. Here's the content of server.py: import cherrypy import os import threading class Root(object): ...

URL Construction with RxJS

How can I efficiently create a urlStream using RxJS that incorporates multiple parameters? var searchStream = new Rx.ReplaySubject(1); var pageStream = new Rx.ReplaySubject(1); var urlStream = new Rx.Observable.create((observer) => { //Looking to ge ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

jQuery Autocomplete - struggling to pinpoint the exact location where the width of the suggestions div is being defined

I have successfully implemented jQuery Autocomplete, but I am facing an issue with adjusting the width. Currently, it is set to 268px in Firebug, however, I would like it to be 520px. After checking the stylesheet, I couldn't locate where the width o ...

When trying to reference a vanilla JavaScript file in TypeScript, encountering the issue of the file not being recognized

I have been attempting to import a file into TypeScript that resembles a typical js file intended for use in a script tag. Despite my efforts, I have not found success with various methods. // global.d.ts declare module 'myfile.js' Within the re ...

The following MongoDB errors unexpectedly popped up: MongoNetworkError: connect ETIMEDOUT and MongoServerSelectionError: connect ETIMEDOUT

I've been working on a React and NextJS App for about a month now, utilizing MongoDB as my database through MongoDB Atlas. I'm currently using the free version of MongoDB Atlas. For the backend, I rely on NextJS's api folder. Everything wa ...

angular-ui-tab-scroll: Odd spacing between blocks and tabs, each separated individually

Greetings! I would like to express my gratitude for this wonderful library! However, I am encountering an unusual issue when trying to wrap a tabset with tabs that are included separately. This can be done either by adding individual tab elements manually ...

Automatically install modules during the execution of the Node Webkit build process

After developing a Node Webkit application, I used NW-Builder to generate the run files. The app's size ended up being quite large at 200MB due to the numerous modules utilized. My question is whether it is feasible to create an installer that will f ...

Trouble loading CSS file in Vue library from npm package

When using vue-cli to build a library (npm package) that functions for both SSR and client-side, everything seems to be functioning correctly except for one issue; the CSS only loads if the component is present on the page being refreshed. However, when ac ...

Switching React components with const

Having some difficulties with the React Switch feature. Attempting to create a layout within another layout, and so far, everything seems to be functioning correctly. import React from "react"; import {Redirect, Route, Switch} from "react-router-dom"; imp ...

Tips on Guaranteeing AJAX Requests are Successfully Called in Sequential Order and Receive Responses in the Same Sequence

What is the best way to guarantee that AJAX requests are executed in a specific order and receive responses in the same order? ...

Retrieve the location of the selected element

We are faced with the challenge of determining the position of the button clicked in Angular. Do you think this is achievable? Our current setup involves an ng-grid, where each row contains a button in column 1. When the button is clicked, we aim to displ ...

What is the best way to enable the user to scroll smoothly while new data is continually being added to the screen?

I'm attempting to develop a chat feature where the scroll automatically moves down when new messages are received by the user. However, I've come across an issue while trying to allow users to manually scroll up. Every time I scroll up and a new ...

What's the best way to make a toast notification appear when an API call is either successful or encounters

Seeking guidance on incorporating toast messages within an Angular + Ionic 6 application... My goal is to display a toast message in response to events such as clearing a cart or submitting an order, with the message originating from an API call. While a ...

Vue.js is experiencing issues with updating attributes within nested v-for loops

Exploring the realm of vue.js and react, I am currently in the process of adapting a basic editable HTML table example found in a React book to further my understanding of Vue. Here is a breakdown of what occurs within the code: User clicks on a td elem ...

What are the steps to retrieve historical stock data for over one year using Yahoo Finance YQL query?

I am currently using a Tableau web connector to retrieve stock price data. Here is the source code: <html> <meta http-equiv="Cache-Control" content="no-store" /> <head> <title>Stock Quote Connector-Tutorial</title> <sc ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Using a function with a parameter as an argument in an event handler

Imagine you have the code snippet below: $('#from').focus(listExpand(1)); $('#to').focus(listExpand(3)); I am facing an issue as the code is not behaving as expected. I believe the problem lies in passing a function result instead of ...

Checking for the winner in a JavaScript tic-tac-toe game

Here is the code snippet for a tic-tac-toe game: $(".square").one("click", function() { if( gameOver == false ) { sq1 = $("#sq1").text(); // captures the value of squares after being clicked. sq2 = $("#sq2").text(); //and so on for all 9 squares } / ...