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

Babelify is having trouble transpiling JSX code within the node_modules directory

I have successfully set up Babelify to transpile jsx code to js, and I've created node_modules before, allowing me to link them without a specific file path, just the package name. However, when I add jsx code within my node_module code, babelify flag ...

What is the best way to link assets within an Angular custom element (Web Components)?

After successfully creating a web component and referencing an image from my asset folder, everything was running smoothly on my local environment. However, when I published my custom element to Firebase hosting, I encountered some issues. When trying to ...

What is the best way to fetch and convert information from an API to display on a website?

I am encountering an issue while trying to retrieve data from an API. Below is my code with a fabricated access code. $(function () { var $data = ('#data'); $.ajax({ type: 'GET', url: 'http://api.openweathe ...

What is the best location to specify Access-Control-Allow-Origin or Origin in JavaScript?

After researching, I found out that I need to set my Access-Control-Allow-Origin or Origin tags. But the question is: where do I actually add these? The suggestions were to use them in the header section. I couldn't find any detailed explanation on t ...

Unusual problem encountered with Chart.js bar chart, image dispersion

On my HTML page, I have integrated a stacked bar chart using the Chart.js library to visually represent data for users. The data changes based on user selection, and the JavaScript function that enables this onclick feature is: function aggLav(){ [... ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

Navigating through elements in an array in node.js

Within my array, I store the languages that users prefer. Here is an example: let language = [] var Lang = "it" language.push(Lang) This process is repeated with various languages. The array would eventually contain these values: language ...

Why isn't this setState function activating?

I am working on creating a versatile notification React component for my application that can be accessed from any part of the code. I have written the following code, where I am attempting to find a workaround for exporting the showNotif function: func ...

Navigating through tabs in a Meteor application: How to maintain the active tab when using the back button

I am working on a multi-page meteor application where each page includes a navigation template. To switch between pages, I am using iron-router. The user's current page is indicated by setting the appropriate navigation link's class to 'ac ...

Structuring files with AJAX, PHP, Javascript, and HTML

Explaining my dilemma in detail might be a bit abstract, but I'll try to do my best. In one of my PHP files, I have HTML code that includes text boxes and a submit button. This file serves as the main page and is named mainHTML.php The text boxes ar ...

Is there a way for me to immediately send data after receiving it?

When I try to perform onPress={() => kakaoLosing() I am attempting to retrieve data (profile) from getProfile using async await and immediately dispatch that data to KAKAOLOG_IN_REQUEST, This is my current code snippet: import { ...

Is it possible to utilize a JavaScript framework within a Chrome extension?

Currently, I am developing a chrome extension that adds a toolbar to the DOM dynamically. In order to find, attach, and manipulate elements, I have been using CSS selectors in JavaScript. However, this approach has proven to be fragile as any changes made ...

Collaborate on React-Native components together!

As a newcomer to the world of react, react-native, and nodejs, I embarked on creating my own node module using npm init. Within this module, I developed a component for styling buttons, packaging it with npm pack and linking it in my application's pac ...

Get your hands on the PDF file with Angular!

Having an issue with downloading a PDF from a WebApi using Angular. The downloaded file is only 15 bytes, even though the data being received from the WebApi appears to be of the correct size when logged as an arraybuffer. The WebApi [HttpGet] pu ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

Convert a boolean value to a string using filter in AngularJS

I am working on an AngularJS app and need to create a filter. In my database, I have a string value that indicates whether the data is active or inactive. I use 'S' for active and 'N' for inactive. I added a checkbox button on my page t ...

Utilize a single array to point to multiple elements

I am curious about the potential to create a unique scenario using JavaScript. Imagine having two arrays: a = [1, 2, 3] b = [4, 5, 6] What if we could combine these arrays into a new array, c, that encapsulates both: c = [1, 2, 3, 4, 5, 6] The intrigui ...