简体   繁体   中英

javascript that executes when leaving page - updating legacy code

Just a bit of background - I was updating a legacy feature that is all javascript as there was new functionality being added to our web app that the legacy feature had to interact with.

While testing this update we noticed that there was an issue when moving from page to page within the web app - the legacy feature is supposed to follow you if it has been activated. Basically the data from the activated feature wasn't being retained. There is some code in there that was supposed to do this. After some investigation it was discovered that it is working as expected in IE/Edge and Firefox but the exit code is not getting executed in Google Chrome and Safari. This might explain why the business wasn't aware of the issue but it's been confirmed that the issue is also in the live site so hasn't been recently introduced as I believe most of the users would be on IE.

The code that was managing the exit functionality was as follows:

    if(window.onpagehide || window.onpagehide === null){
        window.addEventListener("pagehide", storeDataFunction, false);
    } else {
        window.addEventListener("unload", storeDataFunction, false);
    }

With the above code the logic within the storeDataFunction doesn't even execute when you attempt to leave the page.

After some browsing on here and other forums I have updated the above to:

window.onbeforeunload = storeDataFunction;

and made storeDataFunction return null.

This appears to be slightly better in that the storeDataFunction is getting executed when moving pages but deep within it there is an ajax POST to a controller in our web app that stores the data necessary to check if the feature is active and what it has done and this ajax request does not get executed. Again this is only on Chrome and Safari and works fine on IE and Firefox.

So what I'm looking for is a steer. Am I heading down the wrong path using onbeforeunload for what we want to achieve here? Or was the original use of pagehide/unload more appropriate? Are both of those incorrect and there is a better way of doing it? This feature was developed about 7 years ago so I'm not even sure if it ever worked on Chrome or if it did at time of development and some more recent updates in Chrome changed they way it handles page termination.

Thanks in advance.

Looks like Google have updated Chrome to stop XHR during page dismissal.

https://www.chromestatus.com/feature/4664843055398912

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM