Using ajax with onBeforeUnload function fails to function properly on Internet Explorer

I'm curious why this code is functioning differently in Internet Explorer compared to Chrome and Firefox.

    window.onbeforeunload = function()
{
    fetch("http://"+window.location.hostname+"/process_sc.php?cC=" + 1);
} 

function fetch(url) {
    var x = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    x.open("GET", url, false);
    x.send(null);
}   

Answer №1

How can you determine if it's not functioning properly?

Typically, there is very little time between the beforeunload event, the unload event, and the actual exit of the page. When a page unloads, all running scripts are terminated (the browser then closes the window or navigates to a user-provided address, for example).

The issue here may be that the browser doesn't have enough time to send an ajax request before the page is unloaded.

I have come across a few methods to guarantee that your final request before page unload is executed. One approach involves sending a request and then implementing a loop that runs for a specific number of milliseconds, delaying the unload event and ensuring that the ajax request can finish.

window.onbeforeunload = function() {
    fetch("http://"+window.location.hostname+"/process_sc.php?cC=" + 1);
    // in this section, we make the browser wait for 300 seconds before proceeding with the unload
    var t = Date.now() + 300;
    while(Date.now() < t) {};
} 

Answer №2

The issue here is that a GET request is being used instead of a POST request, leading the browser to potentially rely on cached results from the initial request.

This is likely why you are experiencing the behavior of "it only works when I first open IE," as mentioned in response to another solution.

Interestingly, it appears that using AJAX call in onunload is more reliable in IE10 when including the parameter async = false in XMLHttpRequest.open(...), which it seems like you have already implemented successfully.

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

vue-router: Flexibility with Optional Fixed and Path Parameters

Can one route object handle multiple scenarios like: /a/123/b /b My attempted solution is as follows: { path: '(a/:a)?/b', ... } While this works in the Express route tester, it only applies to version 0.1.7 of path-to-regexp. Newer ...

Retrieve JSON or JavaScript property with a string reference

Consider the following JSON array: _htaItems = [ {"ID":1, "parentColumnSortID":"0", "description":"Precondition", "columnSortID":"1", "itemType":0}, {"ID":2, "parentColumnSortID":"0", "description":"Precondition", ...

What is the best way to retrieve a string from a lambda expression?

I am trying to call the function myFunction() and retrieve the source._id value, but I'm encountering issues with the current code. Even though source._id is correctly filled, I am unsure of how to successfully return it in its entirety. Ideally, some ...

Updating the ajax script from 1.8.3 jquery to version 1.9

I am facing an issue with a pagination script that requires jQuery ver. 1.8.3 while my website is using version 1.9.1. Being new to jQuery, I am struggling to figure out how to resolve this. It seems like there might be a syntax problem with ajax and Parse ...

Encountering a [$injector:modulerr] error while attempting to include modules in ZURB Foundation for Apps

I am currently working on a project that involves specific authentication which is functioning well in Ionic. My task now is to incorporate the same authentication system into the admin panel exclusively for web devices. I have already completed the instal ...

Issue with $ symbol in cucumber code snippet

While using cucumber and sublime text 3 to develop some test cases, I encountered an issue with creating a snippet. When trying to call the snippet with the tab button, nothing happened as expected. Upon investigating, I discovered that the problem lies wi ...

Prevent the blocking of Selenium Webdriver by halting the execution of

I am currently facing challenges while writing tests for a web application using Selenium with Ruby. During my automated test, the selenium webdriver triggers a click on an element that executes some Javascript code. This Javascript creates an alert wind ...

Is it possible for object destructuring in Javascript to include dynamic non-rest keys using ...rest?

Suppose we have an object: const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" }; My goal is to filter out specific keys from this object to create a smaller one. I am aware of the following ...

The form submission button fails to function when the onsubmit function returns false

When submitting, I check two fields. If one of the two fields is checked, then I return true; otherwise, I return false. The issue I'm facing is that even when I check one of the checkboxes, the submit button does not seem to work (I use console.log() ...

How can I incorporate @capacitor/core into an AngularJS controller?

import {Plugins, CameraResultType} from '@capacitor/core'; <=============== angular.module('settings.ctrl', ['mn']); angular .module('settings.ctrl') .controller('settingsCtrl', function ( ...

Having trouble with the alias in commander.js not functioning as desired when using the "--help" option

Currently, I am facing a strange issue while working on my project with commander.js. The problem arises when assigning an alias for a command. I looked at some examples mentioned in the reference: Commander.JS Example I decided to create a git-like comma ...

Updating meta tags dynamically for Facebook sharing using Angular 6

I am struggling to dynamically update meta tags such as og:title, og:description, and og:image for sharing on Facebook. I have attempted various methods without success. Initially, I tried setting meta tags with JavaScript like this: var meta = document. ...

React application not functioning on localhost:3000 despite successful compilation with no errors, only displaying the title on localhost but failing to show any content

I recently started developing a new website with React. Everything was running smoothly on localhost until I made some changes, and now the homepage content is not displaying when I visit localhost:3000. I suspect there may be an issue with my routing or s ...

Why is it important to link the image source with the URL in jQuery?

$("<img src="+url+">").appendTo($("body")); The complete data is stored in the url variable, and then it is added to the body element. What is the reason for using the image source to set the url here? ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...

Switch Hidden Input Value When UserControl is in Focus

This task seems deceptively simple, but I'm encountering difficulties trying to make it happen. Within ResidentAddress.aspx, there are two user controls (AppName.ascx and NavButtons.ascx). My goal is to update a hidden input field on NavButtons.ascx ...

Having trouble with fetch() not working in Next.JS while securing API Routes with auth.js

Currently, I am working on a project that involves user authentication using auth.js in next.js. The main goal is to create an API that retrieves specific user information from a MongoDB Database. The website itself is secured with middleware in next.js. I ...

AngularJS UI-Router: Utilizing Optional Parameters

.state('registration', { url:'/app/registration/:ref', templateUrl: 'partials/registration.html', }) This is my configuration for routing using ui-route. It functions properly when I go to localhost:80/r ...

Prevent the context menu from being truncated on the right side of the page

When I right-click in the right portion of my page, my context menu gets cut off. The issue is illustrated here: https://i.sstatic.net/FZguG.jpg I have tried looking for solutions on other StackOverflow pages and trying different demos, but all suggestion ...

Dropping and dragging in the Dojo for the nested lists

Within my HTML code, I am using the Dojo drag and drop feature to sort attributes and move them to another section. However, I am having trouble figuring out how to sort the sections themselves. Here is the structure that I have created: <ul accept=" ...