I'm testing onbeforeunload
behavior using the code snippet from this answer.
var OnBeforeUnload = (function(){
var
FDUM = new Function,
AFFIRM = function(){ return true; };
var _reg = function(msg,opts){
opts = opts || {};
var
pid = null,
pre = typeof opts.prefire == 'function' ? opts.prefire : FDUM,
callback = typeof opts.callback == 'function' ? opts.callback : FDUM,
condition = typeof opts.condition == 'function' ? opts.condition : AFFIRM;
window.onbeforeunload = function(){
return condition() ? (pre(),setTimeout(function(){ pid = setTimeout(callback,20); },1),msg) : void 0;
}
window.onunload = function(){ clearTimeout(pid); };
}
var _unreg = function(){ window.onbeforeunload = null; }
return {
register : _reg,
unregister : _unreg
};
})();
Codes are almost the same. If you look into Developer Console, the output is as follow (make sure you tick the "Preserve log" in Chrome):
in page 1 (did not click "Next Page" hyperlink)
- click "Next Page" hyperlink, console log should display "Navigate to ..."
- click "Previous page" in browser toolbar > choose "Stay on this page" > console log displays "Why you exit?" , "Glad you stayed"
- click "Previous page" in browser toolbar > choose "Leave this page" > console log displays "Why you exit?" , "Navigate to..."
- click "Refresh" in browser toolbar > choose "Don't Reload" > console log displays "Why you exit?" , "Glad you stayed"
- click "Refresh" in browser toolbar > choose "Reload this Page" > console log displays "Why you exit?" , "Navigate to..."
in page 2 (after clicked "Next Page" hyperlink)
- click "Next Page" hyperlink, console log should display "Navigate to ..."
- click "Previous page" in browser toolbar > choose "Stay on this page" > console log displays "Why you exit?" , "Glad you stayed"
- click "Previous page" in browser toolbar > choose "Leave this page" > console log displays "Why you exit?", "Glad you stayed" , "Navigate to..."
- click "Refresh" in browser toolbar > choose "Don't Reload" > console log displays "Why you exit?" , "Glad you stayed"
- click "Refresh" in browser toolbar > choose "Reload this Page" > console log displays "Why you exit?", "Glad you stayed" , "Navigate to..."
You may notice that the message "Glad you stayed" appears in every option on Page 2. My question is: Why do the behavior changed on page 2? and how to make the behavior consistent in both pages in Chrome?
The above results are tested in Google Chrome v47. Behaviors in both pages are identical in Firefox.
Last, the test page is available here (can't use JSFiddle as it cannot reproduce the onbeforeunload
effect)