This issue appears to be quite common, yet I haven't come across any identical cases or solutions that actually work. Therefore, I am adding my voice to the chorus.
The code snippet I have handles the scenario where:
window.onbeforeunload = function() { PubNub.publish(...); };
It sends a message to a PubNub channel when a user exits the current page of a chat forum. We aim to inform others in the room that User X has left. (Please refrain from suggesting alternate designs, such as implementing heartbeat signals for each user; this is simply an experimental project I'm tinkering with.)
While monitoring the channel on another tab, I've noticed that the PubNub message consistently gets published whenever I
- close the tab
and occasionally (both successful and unsuccessful) when I
- refresh by clicking the circular icon in the address bar
but it seems to never occur when I
- click on a link to navigate away
- enter a new URL in the address bar to leave the page
- reload the same URL in the address bar
- use
⌘R
to refresh
Interestingly, even adding return "please don't exit";
in the onbeforeunload handler leads to inconsistent publishing: sometimes the message is sent upon entering the same URL, while other times it isn't.
Could this be a peculiar behavior specific to Safari? If so, are there known workarounds available? Alternatively, could the issue be related to the speed or threading of PubNub.publish(), hindering its execution during an onbeforeunload event? My understanding of how onbeforeunload operates is limited.
(For now, you can access the entire code here. However, if you stumble upon this question in a month's time, please note that the link may no longer be active or may have been corrected.)