Pshivvy
Pshivvy

Reputation: 583

onbeforeunload works different on Chrome than it does on Firefox. I am looking for any potential alternatives

I am trying to add a onbeforeunload to my code so it fires a message that is sent to a server. I am encountering the following issue:

I also know that onbeforeunload is supposed to work when the window is closed, you enter a different website and navigate to that. There are some additional cases which also trigger the function. My site does not work with any of these along with the errors mentioned above.

If there a fix to this? If so, what can I do? I have looked around to fixes but I only get fixes where it prompts the user on whether they want to leave the page or not, I do not want that.

Additionally, I tried adding the function call to onclick on my external links but that is not being triggered on Firefox. I am guessing this is due to the amount of time onbeforeunload has before it is cancelled. If so, there a way around this?

Lastly, if this is not possible with onbeforeunload, what are my other options without prompting the user if they want to leave or not.

Thanks in advance!

EDIT: Here is some code that can be used:

https://jsfiddle.net/985drboy/

Upvotes: 1

Views: 351

Answers (1)

wuerfelfreak
wuerfelfreak

Reputation: 2439

Make sure, that your code sending the message to the server is blocking and not async. If onbeforeunload returns before your message is sent, you get undefined behavior e.g. your message might not be sent if the page is unloads before the sending was complete. The browser continues unloading as soon as unbeforeunload returns.

Upvotes: 1

Related Questions