开发者

Disable onbeforeunload for links

How can I disable onbeforeunload for links?

var show = true;

function showWindow(){
    if(show){      
        alert('Hi');
        return "Hi Again";
    }
}


$('a').click(function(){

    show = false;

});


window.onbeforeunload = showWindow;

This is what I have, but it still shows when I click on an 'a' element

Button code:

<button type="subm开发者_如何学Pythonit" class="submitBtn"><span>Open Account</span></button>


Instead of

show = false;

try

window.onbeforeunload = null;

This will simply unbind the function from the event.


I just ran into the same problem and found a very easy solution:

$("a").mousedown(function() {
    $(window).unbind();
});

This will remove the onbeforeunload event just before the click event is triggered.


Use following code to unbind the event:

javascript:window.onbeforeunload=function(){null}


For some reason, using window.onbeforeunload = null did not work for me.

What did the trick instead was adding and removing the listener accordingly:

let onBeforeUnloadListener;

// Mounting
window.addEventListener('beforeunload', onBeforeUnloadListener = ev => {
  ev.preventDefault();
  ev.returnValue = 'Any';
});

// Unmounting
window.removeEventListener('beforeunload', onBeforeUnloadListener);

This idea came to mind due to using getEventListeners(window), which shown the active beforeunload listeners.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜