Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an event when user navigates away

I need to call a JavaScript/jQuery function which has a few lines of code in it, on a PHP page when the user closes his window/tab or navigates away by clicking a link. I've tried the onbeforeunload function but only the return "blah blah blah;" part executes and everything else is ignored. I've also tried the .unload method from jQuery but for some reason this code doesn't run.

$(window).unload(function() {     alert('blah blah blah'); }); 

Please suggest alternatives. Thanks..

like image 262
CobaltBabyBear Avatar asked Apr 10 '13 12:04

CobaltBabyBear


People also ask

How do I trigger a Beforeunload event?

Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded. You can and should handle this event through window. addEventListener() and the beforeunload event.

How do you trigger an event on click?

If you just need to trigger a click event, you can omit the line that begins with for( . @Parag: Read it again. The loop is to click the same link 50 times, which is what it does.

What is Onbeforeunload event?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


1 Answers

Here is a simple working example. Whatever you return from the unload callback will be displayed in a browser popup confirmation.

Working example sending Ajax request before unload http://jsfiddle.net/alexflav23/hujQs/7/

The easiest way to do this:

window.onbeforeunload = function(event) {     // do stuff here     return "you have unsaved changes. Are you sure you want to navigate away?"; }; 

in jQuery:

$(window).on("beforeunload", function() {     $.ajax("someURL", {         async: false,         data: "test",         success: function(event) {              console.log("Ajax request executed");         }     });     return "This is a jQuery version"; }); 

Look into the Network tab of the browser. You will see how the request is being sent as you wanted to do. Just send the appropriate data.

Bear in mind all operations triggered must be synchronous, so you can only make synchronous ajax requests for instance. However, the above is not entirely reliable for any purpose.

Opt for periodic back-up of user data to localStorage and sync with the server automatically . Keep window.onbeforeunload just as an extra precaution, but not as a main mechanism. It's well known to cause problems.

like image 77
flavian Avatar answered Sep 29 '22 13:09

flavian