0

I need to add an alert before the page closes and all online searches say to directly assign to window.onbeforeunload, as in window.onbeforeunload = function(), and return a string, but this is not working for me no matter what I do.

function unload(evt) {
  return "UNLOAD";
};
console.log("SET1")
window.addEventListener('beforeunload', unload)
window.onbeforeunload = unload;
console.log("SET2");

This issue is ocurring in chrome specifically

Akshay Mulgavkar
  • 1,727
  • 9
  • 22
Alister
  • 453
  • 6
  • 15
  • Possible duplicate of [How to prevent closing browser window?](https://stackoverflow.com/questions/333665/how-to-prevent-closing-browser-window) – Herohtar Jul 30 '19 at 04:17
  • Seems like they can the function to run. I can't even do that. – Alister Jul 30 '19 at 04:19
  • How does your `window.onbeforeunload` function look like and on which browser(s) does the event not working? – Thum Choon Tat Jul 30 '19 at 04:19
  • 3
    No it isn't deprecated, only the "custom text" part is deprecated. It is fully documented [here](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload) – Jaromanda X Jul 30 '19 at 04:19
  • `functionToRunOnUnload()` remove the `()` - there's a difference between running a function (what you do) and referencing the function - which is what you need to do (edit: you changed the code you are using) - you may also want to read the documentation I mentioned earlier to see what you need to do inside the function ... preventDefault is the key – Jaromanda X Jul 30 '19 at 04:21
  • @JaromandaX - please make your comment as the answer – pinaki Jul 30 '19 at 04:23
  • @pinaki - no, it is not the answer, because the problem is what OP is doing in the function – Jaromanda X Jul 30 '19 at 04:24
  • @JaromandaX - sorry for the misunderstanding, i meant that your link already has the answer for what he is doing wrong, so you can change it to a proper answer and he can confirm it. cheers – pinaki Jul 30 '19 at 04:25
  • Apologies, I'm getting frustrated, a more "accurate" version has been posted – Alister Jul 30 '19 at 04:25
  • Also forgot to say, this is for Chrome – Alister Jul 30 '19 at 04:26

0 Answers0