Maison  >  Article  >  interface Web  >  关于捕获用户何时点击window.onbeforeunload的取消事件_javascript技巧

关于捕获用户何时点击window.onbeforeunload的取消事件_javascript技巧

WBOY
WBOYoriginal
2016-05-16 18:09:371243parcourir

Detecting When The User Has Clicked Cancel
One of the things you may want to do is to be notified when the user clicks cancel, aborting a page unload. Unfortunately there's no way to be immediately notified. The best you can do is to set a unique global variable in your "onbeforeunload" event and then look to see if that variable has been set in other functions. There is no way to get an immediate notification that the user has aborted a page unload.
The example code I used above to do an example of an "onbeforeunload" dialog is as follows:

复制代码 代码如下:

var _isset=0;

function demo() {
window.onbeforeunload = function () {
if (_isset==0) {
_isset=1; // This will only be seen elsewhere if the user cancels.
return "This is a demonstration, you won't leave the page whichever option you select.";
}
}
_isset=0;
window.location.reload();
return false;
}

This code defines a global variabled named _isset, and then initializes it to zero. In our "onbeforeunload" event the variable is checked and if it's set to one, no unload dialog box will appear. The only way _isset could ever be one is if the user previously aborted a page unload.

But as you can see this method won't help you if you need to be immediately notified that that the user has finished dealing with the confirmation box. You can detect when it appears on the screen but there's no way to know when the user has finished interacting with it if the user clicked cancel (if the user clicked OK, then of course the unload event will have been tripped).
--------------------------------------------------------------
虽然如此,但还是有高手给出了如下代码 ^^
复制代码 代码如下:

BR>"http://www.w3.org/TR/html4/strict.dtd">




onbeforeunload test



onbeforeunload test





复制代码 代码如下:


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn