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

Navigate to the following slide by clicking on BxSlider

Looking to enhance the navigation on my slideshow by using the slide itself as a next button, instead of relying on traditional prev/next controls. Although it seems like a simple feature to implement, I'm struggling to make it work. This is my curre ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

Navigating between different components in React Router V4 allows for seamless transitions without having to reload the

I am currently learning React with React Router V4 and I have a specific scenario in mind that I would like to achieve, possibly illustrated by the image below: Click on the "Next" button Trigger a click event to Component A ("button got clicked") Upon c ...

Confirm that the form is valid when a specific requirement is fulfilled

I am currently working on a credit card project that involves using a JavaScript function called validateCreditCard to validate credit cards and determine the type. The idea is to store the credit card type as the value of a hidden input field called cardT ...

Tips for preventing window.location from becoming relative to the file

Despite my best efforts, I couldn't figure out why this issue was occurring or how to resolve it. Here is the code in question: window.location.href=("www.google.com"); The intended functionality of this code is to redirect to google.com, but inst ...

Guide to adding directional arrow indicators on the Y and X axes of a ChartJS graph

Is it possible to add directional arrows on the Y and X axis of a ChartJS graph? I'm seeking advice or tips on how to achieve this. Below is the code snippet for creating the chart. var ctx = $("#mycanvas"); var LineGraph = new Chart(c ...

Is there a special Angular technique to ensure a div remains scrolled to the bottom of its items?

In this interactive demonstration, you can see how jQuery can be utilized to create a terminal-like feature. This functionality ensures that as new items are added to a scrollable div, the scroll automatically locks at the bottom. Pay close attention to l ...

Encountering an issue while trying to import the D3.js library into my React.js application

I'm having trouble with properly importing the d3.js libraries in my react.js app. I am using import * as d3 from 'd3' to import everything and store it in the d3 namespace, but I keep getting an error that says - Cannot read property ' ...

Find out which way the user is scrolling in your React js application

I'm struggling to determine whether the scroll event is moving up or down, and I haven't been able to find a solution yet. import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; const Nav ...

Create a dynamic animation using Angular to smoothly move a div element across the

I currently have a div with the following content: <div ng-style="{'left': PageMap.ColumnWrap.OverviewPanelLeft + 'px'}"></div> Whenever I press the right key, an event is triggered to change the PageMap.ColumnWrap.Overvie ...

Error code "ER_BAD_FIELD_ERROR" was encountered with errno 1054 and sqlState "42S22" in index 0 while using MySQL with Angular and managing sessions

When I log in, the following code is executed: <div ng-include="'partials/navbar'"></div> <form name="form" ng-submit="login(form)"> <div> <input type="text" placeholder="Email" ...

Transferring an array from PHP to Javascript using GET method

Can someone help me figure out how to pass an array to Javascript after it sends a GET request to PHP? I've got the data sending and retrieving down pat, but now I'm stuck on how to send the data back as an array. Here's what I have so far: ...

How can I use AngularJS resource to fetch data from a URL that requires both query parameters and post data?

Requirement: To send data to an endpoint using a post of data, include the startdate and endate in the querystring of the url. Here's an example: The data payload should only contain the locationIDs and Criteria as shown below. The Resource Definiti ...

JavaScript for Altering Viewport/Screen Width

Lately, I've been experimenting with creating a responsive button for our new website. The goal is to adjust the body width to 460px, simulating how our site would appear on mobile devices. While researching, I came across a technique that utilizes if ...

Upon successful authorization, the Node Express server will pass the access token to the React client app via OAuth in the callback

I am currently working on a node server that authenticates with a third party using oauth, similar to how Stack Overflow does. After authorizing the request and obtaining the access token and other essential information from the third party, my goal is to ...

Exploring unique forms with the turfjs polygon difference() function

While implementing the difference() function for my polygon map, I encountered a problem where unexpected shapes would appear or disappear when zooming in on the map. These shapes should not be there. The polygons involved are of type MultyPolygon and Poly ...

I am puzzled as to why my ajax script is giving me a 404 error even though the URL appears to be correct

Even though it's not a cross-domain problem, Ajax is returning a 404 error code. In my TIZEN Web application project, I am trying to make an ajax request to a WebService that contains functions necessary for the project. Initially, the xhr.status was ...

Exclusive Modal Pop-Up for First-Time Visitors - Utilizing Bootstrap, PHP, and JavaScript

Seeking assistance from the community as I have exhausted my online research efforts. I am currently working on implementing a welcome bootstrap modal in a php environment. Despite being new to php and js, I have managed to make it pop up only once using ...

Customize your Angular UI Bootstrap Datepicker with unique buttons - here's how!

Currently, I have a datepicker with clear and close buttons. I tried using the append function to add more buttons to this datepicker, but it didn't work because the content is not loaded until we click the icon since it's a popup datepicker. Is ...