What is the process for running a function upon closing a tab?

Here is the function I am using to detect when a form is closing:

    window.onbeforeunload = function (e) {

        var y = e.pageY || e.clientY; //window.event.clientY; //

        if (y < 0) {
            return 'Window closed';
        }
        else {
            return 'Are You Sure Wants To Close Form?';
        }
    };

Currently, it only displays a popup with the text "Are You Sure Wants To Close Form?". However, I would like to perform a task if the user chooses to leave the page. How can I achieve this?

Answer №1

Take a look at this:

Our typical approach won't work here, we'll have to employ a little trick:

Code Example

var timeout;
$(window).on('beforeunload', function (){
    timeout = setTimeout(function() {
        alert('find a different function to run in my place!!!!');
    }, 1000);
    return "goodbye!";
});

Answer №2

It's important to note that the functionality of window.onbeforeunload is not consistent across all browsers, making it unreliable for ensuring your code runs before a user leaves your page.</p>

<p>Therefore, it is advisable not to depend on window.onbeforeunload for critical tasks.

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

Encountering difficulties while attempting to delete with a router.delete command - receiving a 404 not

Within my application, I am passing the request parameter 'id' in the router.delete method and communicating it with the Vuex service. However, when triggering the action, an API call is made but it results in a 404 error indicating "not found" a ...

utilizing switch case to handle login and registration of new users in a PHP application

I attempted to implement a switch case with login and new user submit button functionality, but I am only seeing the default case option with its corresponding values. Below is the code snippet: <?php switch ($_POST['submit']) { ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

To activate the speech synthesis feature with a message, you must click a button for it to work

The issue with the code snippet below is that the function "window.speechSynthesis.speak(msg)" does not produce any sound output unless the button is clicked first. Only after clicking the button, the "Hello" message works as intended. Any attempts to call ...

I'm a beginner with Angularjs and I attempted to populate multiple JSON values, but unfortunately, it didn't work as expected

<div ng-controller="studentController" ng-repeat = "student in students | unique = 'RollNo' " > <table class="profile-info"> <tr> <th>Enrollment Number</th> <td> ...

Update various components within a container

I have incorporated a function that automatically loads and refreshes content within a div every 10 seconds. Here is the script: $(function () { var timer, updateContent; function resetTimer() { if (timer) { window.clearTimeout(timer); ...

The chart appears oversized in the vue js. How can I make it smaller in size?

I recently integrated a line chart from Chart JS into my Vue.js project, but the chart is taking up too much space on my webpage. I'm looking for ways to make it appear smaller and more compact. This is my first time working with charts in Vue.js, so ...

Parsing JSON within an HTML document

It seems like what I'm attempting to do should be straightforward, but for some reason, I can't seem to get it to work? Let's say I have the following JSON file named jsonFile.json: { "level1": "elemet1", "level2": "element2", ...

What is a way to adjust the width of fixed columns in a Bootstrap 4.0 responsive table?

I've been struggling to make this work despite following similar questions and answers. I attempted to adjust the column width by directly setting each one, but nothing seems to change! <thead style="white-space: nowrap"> ...

What are the reasons behind the lack of smooth functionality in the Bootstrap 4 slider?

My customized bootstrap4 slider is functional, but lacks smoothness when clicking on the "next" and "prev" buttons. The slider transitions suddenly instead of smoothly. Any suggestions on how to fix this? Here is the code for the slider: $('.carous ...

Is it possible to access a component's function from outside an ng-repeat in Angular 1.5?

Recently delved into learning Angular 1.5 components and testing out some fresh concepts, however, I'm struggling to wrap my head around this particular issue: Here's the code snippet from my Main: angular.module('myapp',[]) .contr ...

Top Ranking EF Value Recorded

In my search for the highest record based on a specific field, I've encountered that the Max() extension returns only the given type. For example: o.Max(i => i.CreatedDate) // returns date It provides the maximum date value instead of the entire ...

Attempting to modify the background color of an iFrame in Internet Explorer

I am experiencing an issue with my webpage where the iFrame is displaying with a white background in IE, while it shows up with a blue background in Firefox and Chrome. I have attempted various solutions to make the background of the iframe blue or transpa ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

One way to achieve the same functionality as onclick in an Ajax call using

I have two JSPs. In the first JSP, I am making an ajax call and receiving data (Ajax body) from the second JSP. However, I am unsure of how to execute jQuery when an argument is present in the function. Everything works fine without an argument. In the ...

Transferring files via Bluetooth on PhoneGap

As someone new to phonegap, I'm interested in transferring text files from one device to another using Bluetooth within the platform. I've looked at several examples but haven't found a solution yet. I've come across some examples that ...

Struggling to create an accurate regular expression for validating URLs

I am currently working on a project where I need to create rules to avoid accepting incorrect URLs. I have decided to use regex for this purpose. My URL format is "http://some/resource/location". This URL should not contain any spaces at the beginning, m ...

Incorporating MongoDB collection elements into a Discord embed display

I am trying to include my collection of documents in an embed using MongoDB's ForEach function. However, I have noticed that when attempting to add a field to the embed within the forEach loop, it appears that the code sends the message first and the ...

Is it possible for a script tag added to an element to execute prior to the following line following the .append() method

After retrieving an HTML document from the server and storing it in a variable called data, I then add the content to a <ul> element on the page. The structure of the data is as follows: <script> hasNext = true // this global variable < ...

Is it a jQuery AJAX problem? Could it be related to cross-domain issues?

I'm currently working on implementing a tracking script that utilizes AJAX through JQuery. This is specifically for my personal use, so while aesthetics are not important, functionality is key. Essentially, I am incorporating scripts onto domains ow ...