Cancel your subscription to a PubNub channel when the unload event occurs

Currently, I am developing a multiplayer game in Angular utilizing the PubNub service along with the presence add-on.

One of the challenges I am facing is detecting when a player unexpectedly leaves the game. This is crucial for sending notifications to other players and properly terminating the game. My attempt to unsubscribe a user upon refreshing the page or navigating to another URL is not working as expected. More specifically, while using Chrome, unlike FireFox, no presence event is triggered, suggesting that the user was not successfully unsubscribed before leaving the page.

Below is the snippet of code I have been trying:

 $(window).bind("unload",function(e) {

    PubNub.ngUnsubscribe({channel:$scope.game.channel});
    e.preventDefault();

    }); 

I acknowledge that relying on beforeunload and unload events can be problematic due to poor browser support, which might be the root cause of the issue. If this is indeed the case, I am wondering if there are alternative cross-browser detection methods that I could implement instead?

Answer №1

Finding a foolproof method to detect the browser closing can be quite challenging. While the "beforeUnload" event is often recommended, it may not work consistently on mobile browsers. In PubNub, one approach to handling this issue is by setting a heartbeat when subscribing (). This heartbeat determines the duration PubNub should wait after an abrupt disconnect (such as browser closure) before considering a user timed out. By default, this timeout period is set at 320 seconds but can be adjusted to as low as 6 seconds (greater than 5). Although it won't provide real-time detection, you will receive a presence "timeout" notification 6 seconds after the browser shuts down. Keep in mind that having a lower heartbeat value could potentially impact battery life, so exercise caution.

Additionally, while the link provided directs to the JavaScript API documentation, it's worth noting that the angular ngSubscribe function offers similar functionality with most of the same arguments.

I hope this information proves useful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send PS3 through user agent for redirection

If a user is accessing the site using a PS3, I want them to be redirected to a different webpage Below is the code snippet I have been attempting to use: <script language=javascript> <!-- if ((navigator.userAgent.match(/iMozilla/i)) || (navigato ...

In the context of Express, how are "static" and "non-static" defined?

The Express documentation explains that the express.static() middleware is used to serve static files like images, CSS, and JavaScript. However, when serving a front-end React app using express.static("some_build_dir"), which includes JS files ...

Using AngularJS and the ng-show directive, you can set a <div> element to

Objective: My aim is to show the content of a div according to the status of checkboxes, while also ensuring that these divs are visible by default If I have this code snippet: <html> <head> <script src="https://ajax.googleapis.com/ajax/li ...

Using Waveskeeper for Verification: Solutions for Resolving the 'Waves is not defined' Issue

I'm currently working on creating a page that authenticates users with Waveskeeper. I have successfully installed the Waveskeeper addon on Chrome, but I keep encountering an error: ReferenceError: Waves is not defined. I've attempted to use both ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

Using Regular expressions in JavaScript to eliminate content between two HTML comment tags

I am currently dealing with two HTML comments in this format: <!--Delete--> Blah blah blah blah <!--Delete--> I need to remove these comments, along with any characters and newlines. I am utilizing JavaScript and Grunt for this replacement ta ...

Troubleshooting not locating view files in ExpressJS and implementing client-side JavaScript and CSS deployment in ExpressJS

My JavaScript file is located in the same directory as my HTML file, and I am trying to render it. I'm unsure of what I may be missing. How difficult could it possibly be? var express = require('express'); var app = express(); app.engine( ...

Passing data from an API in Vue.js to a different page

I'm a beginner with Vue Js and I'm looking for guidance on how to send data between two components. Currently, I am working on a Vue app that fetches a list of users from an API and displays them. My goal is to transfer data between these compone ...

Providing secure access to Apostrophe-CMS S3 assets and attachments via HTTPS

Currently, I am utilizing Amazon S3 to deliver both my static assets and user uploads within the context of apostrophe-cms. While my site is loading via https, all of my assets appear to be loading using http. I have set up a cloudfront distribution at th ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this: index.ejs <!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <bo ...

What is the best way to stylize a date using Bootstrap-datepicker?

While this topic is well-known, I have a slightly more complex question regarding it. I have gone through the documentation here. My goal is to display the date in French format (dd/mm/yyyy) and save the value in US format (yyyy-mm-dd). Additionally, I nee ...

The issue with MaterialUI Select's set value is that it consistently falls outside the expected

I'm currently working on a MaterialUI Select component where I am dynamically handling the value parameter. However, I'm facing an issue where even though I set a valid value from the available options, it always shows as out of range. SelectInp ...

Avoiding default action on keyboard tab event resets cursor position while typing consecutively

Issue with cursor position resetting to start when tab is the last key pressed I am working on a chrome extension for Gmail using React and need to customize the behavior of the tab key. I have found that using preventDefault and stopImmediatePropagation ...

Finding a way to reference multiple components within a mapping function

In order to set a ref to each project within the map function, I am trying to pass forwardRef from child to parent. At the moment, I am only able to get a single Project. However, I need to set refs to an array list so I can work with it. Below is what I h ...

How can you apply a class to a different element by hovering over one element?

Is there a way to darken the rest of the page when a user hovers over the menu bar on my website? I've been playing around with jQuery but can't seem to get it right. Any suggestions? I'm looking to add a class '.darken' to #conte ...

Is PHP-generated HTML not responding to external Javascript?

I have been attempting to create a form where, upon checking a checkbox, the onClick() event will enable a select option. Below is my PHP code: function generateOption() { for($x = 0; $x < 10; $x++) { echo "<option value='".$x."'> ...

If a second instance is hidden, SVG will appear as a mysterious black box

Two separate div elements each contain an identical SVG graphic. If I hide the first div by setting it to "display: none", the SVG in the second div appears as a gray box. This issue is present in both Firefox and Chrome browsers. Any insights into why ...

Tips for extracting the chosen value from a dropdown list within a table cell using JavaScript

Here is an example of an HTML element: <td> <select> <option value="Polygon 47">Polygon 47</option> <option value="Polygon 49">Polygon 49</option> </select> </td> I am looking for a ...

Why is Node.js unable to locate my files?

I'm currently utilizing Node.js as my server, and I'm encountering some difficulties in serving my JS and CSS files. For some reason, index.html is unable to locate them. Whenever I try to load up my browser, I encounter the following error: htt ...