admin管理员组

文章数量:1291688

I have a few links in my page and I want to call a function when the page is trying to reload.

I tried

$(window).unload(function() {
  alert('Handler for .unload() called.');
});

It is not working.

I have a few links in my page and I want to call a function when the page is trying to reload.

I tried

$(window).unload(function() {
  alert('Handler for .unload() called.');
});

It is not working.

Share Improve this question edited May 23, 2012 at 6:28 oers 18.7k13 gold badges68 silver badges76 bronze badges asked May 22, 2012 at 10:33 Kanishka PanamaldeniyaKanishka Panamaldeniya 17.6k31 gold badges127 silver badges194 bronze badges 3
  • "Not working" in what browser? – raina77ow Commented May 22, 2012 at 10:37
  • @raina77ow -> google chrome......... – Kanishka Panamaldeniya Commented May 22, 2012 at 10:40
  • @KanishkaPanamaldeniya: what actions(s) do you want to perform onunload? Also, bear in mind unload is called: "... when the user navigates away from the page... clicked on a link... typed in a new URL... The forward and back buttons [and] ... closing the browser window [and] ... a page reload will first create an unload event." (Source). – c24w Commented May 23, 2012 at 19:16
Add a ment  | 

3 Answers 3

Reset to default 4

Console: Blocked alert('Handler for .unload() called.') during unload. (in Chrome)

I assume this is blocked for user-experience reasons.

If you try console.log('Handler for .unload() called.'); the call is made successfully.

Edit: see $(window).unload is not firing

you can try:

window.onbeforeunload = function() {

}

window.onbeforeunload = unloadMessage;

   function unloadMessage() {
           //do your codeing here...
   }

本文标签: javascripthow to call a function before page reload jqueryStack Overflow