简体   繁体   中英

How to use eventlisteners in functions?

I need to ask confirmation from the user before unloading the page. If I do this in JS, it works:

window.onbeforeunload = function () { //close confirm
    return '';
}

but when I place it into a function to make this more flexible, I seems to be not registered:

function sth()
{
    window.addEventListener('beforeunload', closeConfirm, false);
}

function closeConfirm()
{
    return '';
}

Can someone please tell me the difference? Removing is also not working in a function, after event was registered outside the functions in plain JS. sth() is called by pressing a button. I need to enable this eventlistener on login, and remove on logout or timeout, but I cant make it work with function calls, but just when the page loads.

---REFRESH--- Example: https://jsfiddle.net/6mvuet1h/1/

If you comment out the 2-4 lines, this is not working.

So I'm editing my answer, because I misunderstood your problem before.

On beforeundload mdn page we can read that some browsers (chrome included) need event.returnValue to be set. Some other browsers need event.preventDefault() to be called. So your closeConfirm function should look like this:

function closeConfirm(event)
{
    event.preventDefault();
    event.returnValue = '';
    return '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM