Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onunload is not working properly in Chrome browser. Can any one help me?

I have written this code

function winUnload() {
    alert("Unload Window");
    MyMethod();
}

window.onunload = function() { winUnload(); }

This code is working fine in IE and Firefox. But this code is not working in Chrome. Both the statements alert("Unload Window"); and MyMethod(); are not working.

like image 597
Imran Avatar asked Oct 17 '11 13:10

Imran


People also ask

What is window Onunload?

onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.). Note: The onunload event is also triggered when a user reloads the page (and the onload event).

What is the difference between Onbeforeunload and Onunload?

onbeforeunload Below are my findings on the iPad; Using window. onunload , I am able to get an alert when user navigates to a different page from myPage. html (either by clicking on some link or doing a Google search while on myPage.

What triggers Onbeforeunload?

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.


2 Answers

There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.

But what is possible (AFAIK):

  1. Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
  2. Return a simple string (in beforeunload event), which triggers a confirm box, which asks the user if s/he want to leave the page.

Example for #2:

$(window).on('beforeunload', function() {     return 'Your own message goes here...'; }); 

Demo: http://jsfiddle.net/PQz5k/

like image 200
Armin Avatar answered Sep 18 '22 06:09

Armin


I know this is old but I found the way to make unload work using Chrome

window.onbeforeunload = function () {   myFunction(); }; 
like image 23
Carlos Avatar answered Sep 20 '22 06:09

Carlos