0

I have an onberforeunload method which is correctly alerting the user when they are trying to close the tab or the browser using the follwoing code:

window.onbeforeunload = function(event) {

                event.returnValue = 'Are you sure you want to leave/';
                console.log(event.returnValue);

    };

I have discovered that the onberforeunload is not being called when I click a hyperlink on the page. The warning message I want to display isn't appearing and the page is loading freely.

I have searched for many ways to create a popup for when a hyperlink has been selected but they all deal with one or groups of hyperlinks in div tags. I wish for a popup to display if any hyperlink is selected.

Why isn't onbeforeunload catching the exiting of the page through a hyperlink? Is my understanding of onbeforeunload wrong that it should be catching hyperlink exits?

UPDATE

I have updated the code to the following:

window.onbeforeunload = closeIT;
function closeIT() {
        return 'here';
        if(searchOnGoing){
            return 'Ifs you leave the Youtube History page now the application will not finish';
        }

};

It is still not working for hyperlinks and working for browser and tab closure. I am running this as part of a content script in a chrome extension which is injecting the content script into the page. Would this have an effect on it?

I also have an onunload following,i am wondering would this also have an effect on it?

window.onunload = function(event){
            //Do something
    }
Bawn
  • 509
  • 3
  • 13
  • 36
  • It should work for hyperlinks as well (see [this example](http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/onbeforeunload.htm)). I think you just need to change your `event.returnValue ...` to a traditional `return` statement (and move it after the log). – jeffjenx Mar 21 '16 at 20:46

2 Answers2

1

Actually, it should trigger. Do you catch the event somehow via a click-event-listener? Anyway, you could show an alert with help of a click-event listener. Following code-snippet is copied from a similar question: how to detect if a link was clicked when window.onbeforeunload is triggered? Here the question was, in contrast, how to prevent the beforeunload event when links are clicked.

var link_was_clicked = false;
document.addEventListener("click", function(e) {
  if (e.target.nodeName.toLowerCase() === 'a') {
    link_was_clicked = true;
  }
}, true);

window.onbeforeunload = function() {
  if(link_was_clicked) {
    link_was_clicked = false;
    return;
  }
  //other code here
}
Community
  • 1
  • 1
0

The following snippet correctly uses onbeforeunload.

    <body onbeforeunload="return myFunction()">
    
    <a href="google.com">Click me!</a>
          
    <script>
    function myFunction() {
        return "Please don't go!\nThis works beautifully!";
    }
    </script>
StardustGogeta
  • 3,331
  • 2
  • 18
  • 32