As a lot before you - you missed the onbeforeunload event handler...
Read here:
https://developer.mozilla.org/en-US/docs/WindowEventHandlers.onbeforeunload[
^]
From that you can understand that the event handler is used to set the message displayed to user upon leaving the page...
At this point it not even sure he will leave the page at all as he can choose cancel too!
So - if your code WAS working you would be sorry for that...
Do a little article search in CP, you will find some help...