The JavaScript onunload event handler

Despite all my research, I'm still unable to solve this issue. My task involves executing some functions when a user leaves my page. To achieve this, I utilized window.onbeforeunload to warn the user about leaving the page and window.onunload to initiate the tasks. However, I encountered a problem - the onunload function does not complete before the page is closed.

In an attempt to resolve this, I experimented with the following code:

        window.onunload = function() {

            //freezeScreen(5000);

            console.log("destroy finished 1/8");

            $.each(_tabClassObj, function(index) {
                _tabClassObj[index].destroy();
            });
            console.log("destroy finished 2/8");
            _tabClassObj = {};
            console.log("destroy finished 3/8");
            _terminalTabCounter = 0;
            console.log("destroy finished 4/8");
            window.onbeforeunload = null;
            console.log("destroy finished 5/8");
            window.onunload = null;
            console.log("destroy finished 6/8");
        }

My console log displays:

destroy finished 1/8
WebSocket is already in CLOSING or CLOSED state.
WebSocket is already in CLOSING or CLOSED state.
WebSocket is already in CLOSING or CLOSED state.
WebSocket is already in CLOSING or CLOSED state.
WebSocket is already in CLOSING or CLOSED state.

I tried delaying the browser UI closure using the freeze function, which delays shutdown by 5 seconds... yet the issue persists. I also attempted using setTimeout without success. Can you identify what's causing the problem? Any guidance would be appreciated.

Answer №1

When working with Blaze in the view Layer, you can utilize the onDestroy method to define any specific actions that should be taken before navigating away from the current URL.

Template.xxx.onDestroy( function() {
    // Add your custom logic here.
});

Answer №2

My attempt to achieve what I wanted with a JavaScript event didn't go as planned. In order to address the issue of my Meteor server losing connection when the client closes their browser, I developed a ping system like this:

// Both sides
TelnetUserConnections = new Meteor.Collection('TelnetUserConnections');

// Client side
Meteor.startup(function(){
    // Timer to refresh the heartbeat on the server
    Meteor.setInterval(function () {
        Meteor.call('keepAlive', Blaze._globalHelpers.currentUserId());
    }, 5000);
});

// Server side
Meteor.methods({
    "keepAlive": function (user_id) {
        if (!TelnetUserConnections.findOne({user_id: user_id})) {
           TelnetUserConnections.insert({user_id: user_id});
        }
        TelnetUserConnections.update({user_id: user_id}, {$set: {last_seen: (new Date()).getTime()}});
    }
});

Meteor.setInterval(function () {
    // Perform necessary actions when a user hasn't sent a ping in 20 seconds
    var now = (new Date()).getTime();
    TelnetUserConnections.find({last_seen: {$lt: (now - 20 * 1000)}}).forEach(function (user) {

        /* here is where I handle clean up tasks */

        TelnetUserConnections.remove({_id : user._id});
    });
});

Hopefully this information can be helpful.

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

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...

Why is the "module" field used in the package.json file?

Recently, I came across certain npm packages such as vue that contain a module field in their package.json files. Interestingly, the official documentation for package.json does not mention the module field - is this some kind of convention being followed ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

Having trouble with script tag not loading content in Next.js, even though it works perfectly fine in React

Currently, I am attempting to utilize a widget that I have developed in ReactJS by utilizing script tags as shown below- React Implementation import React from "react"; import { Helmet } from "react-helmet"; const Dust = () => { ...

Error: The module PosModel is not defined

Recently, I took over the responsibility of working on the models.js file for the point_of_sale module. My task was to add a new model by integrating the following code: openerp.dewieuw = function(instance, local) { //module is instance.point_of_sale var ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Passing a JSON object as a parameter in a dynamically created element's click event using JavaScript/AngularJS

How to pass a JSON object as a parameter in the click event of a dynamically created element using JavaScript and AngularJS? var _dataObj = "{"sor_SourcingAgentId":1,"sor_Name":"xx"}" var _dynHtml= '<input type="button" ng-click="fnSelectcustom ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

Vue.Js for a Single Page Application utilizing Two Data Sources

Currently, I am working on developing a Single Page Application using vue.js. My project consists of 2 bundles of pages stored in separate S3 buckets - one public and one private. The public bundle is meant to be accessible to all users, while the private ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Were you intending to import the file firebase/app/dist/index.cjs.js?

Encountering the following error message: Error: Directory import 'C:\Users\My Name\Documents\Code\WebProjects\nextfire-app\node_modules\firebase\app' is not supported when resolving ES modules import ...

A guide to resizing images in Node.js prior to using the writeFile function

var file_path = files.file.path; fs.readFile(file_path, function (err, data) { fs.writeFile(file_path, data, function (err) { res.end(JSON.stringify({ message: 'file uploaded successfully', success: true }); }); }); I exp ...

Steps to incorporate this jQuery script

After receiving a solution to my problem, I'm struggling with how to actually put it into practice. $(function(){ $.get('file1.php', function(data){ $('#dropdown1').html( data ); }); // when dropdown1 is chang ...

Specialized hover mission

Do you have a question? Imagine you have 3 spans where the default color is black. When you hover over a span, its color changes to red. But what if I told you that at the start, the first span has an orange color. Now, I want to hover over the orange on ...

Getting the selected item from a dropdown menu and including it in an email

While working in React, I have successfully created a contact form that includes fields for name, email, and a message box. When the form is submitted, these three items are sent as expected. However, I am facing difficulty in sending a selected item from ...

What could be the reason for the bottom edge of my central diagonal image having a darker border?

I can't figure out why the border on the bottom edge of my image is darker. You can check out the demo here. To get a closer look at the issue, you can open a software like GIMP and zoom in on the following image to see the difference in values: http ...

Utilizing modal functionality in CakePHP 3 (or: Incorporating JavaScript within Controllers)

I have a typical form that was created using cake/bake. After the form is submitted, my controller checks a simple condition: If condition A is met, it will just save the data using patchEntity($foo, $this->request->getData()) If condition B is me ...

Issues with Content-Security-Policy Implementation in Next JS and AMP Technology

While developing an AMP application with Next JS, everything seems to work perfectly in localhost. However, upon moving to the production environment, I encountered errors related to AMP not being allowed to load its workers. The initial error message is: ...

Obtain the value from the controller of the amazing-rating component

Currently utilizing the amazing Rating AngularJS library available at https://github.com/bandraszyk/awesome-rating I am interested in understanding how to retrieve the selected value and store it in my controller. The $scope.rating is returning undefined ...

Sending an array of properties to a child component

I am attempting to pass an array of objects from a parent component to a child component as a prop, then iterate over it using map and display the items in the child component. However, when I try to use map on the array nothing is happening, even though ...