React, Detect if user is going to leave the current page - javascript

Hello and thank you for your time!
I was learning by following a React course: https://app.pluralsight.com/library/courses/react-flux-building-applications/table-of-contents
And it looks like the React Router API has changed a lot since the course was filmed.
In the course it is taught how to use willTransitionFrom and willTransitionTo which both look like they are deprecated:https://github.com/ReactTraining/react-router/issues/1388
I would like to follow along, and I have tried to do the detect if the user is going to leave the current page. I have done:
window.addEventListener('beforeunload', (event) => {
if (!(window.confirm("DO YOU really want to exit a fun page like this?"))) {
event.preventDefault();
}
});
And also:
window.onbeforeunload = (event) => {
if (!(window.confirm("DO YOU really want to exit a fun page like this?"))) {
event.preventDefault();
}
};
It looks like neither of them gets fired, because I would like to show the confirm dialog when you try to load another page.
I have read:
How to check if user is refreshing the page or navigating to other page
How to display a pop up, when a user tries to leave the current page?
https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
Thank you for your help.

Try this one (picked from https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload)
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});

Related

Confirmation before leaving/closing of tab?

I'm trying to show a confirmation pop before user close the tab or went to another tab like facebook, gmail, GoDaddy & others do.
My code working for Firefox but not for other browser like chrome, safari etc.
<script type="text/javascript">
var hook = true;
window.onbeforeunload = function() {
if (hook) {
return "Did you save"
}
}
function unhook() {
hook=false;
}
</script>
Call unhook() onClick for button and links
No Block URL
Please help me to get this fixed.
If you take a look at the api of window.beforeunload(), you can see that, though widely the basic unload event is supported, a custom message can only be set in internet explorer and certain versions of some browsers. So just use the normal standard message.
This feature (custom messages) was often exploited by malicous sites to interact with user in a harmful or malipulative way. This is why many browsers don't support this anymore, until some patch removes the threat for users.
Standard message solution:
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});
Look at Ouibounce it helps detect when a user is about to leave the page(It looks at the position of the cursor). You could probably build off this library.

onbeforeunload not working - tried everything

I have tried a lot of things for onbeforeunload and came up with a solution-
window.addEventListener("beforeunload", function(e) {
(e || window.event).returnValue = null;
return null;
});
This seems to work when i navigate away from the current page inside the application, but its not working for which it is intended that is on browser close. i want this to work only on browser close and not on navigating by clicking on other links inside the application. Any leads will be appretiated. Thanks in advance.

How to trigger a function after I close or refresh the browser

I want to update my data on SQL server database after I directly closed or refresh the browser.
Here's my code:
$scope.default = function () {
//Update the data to default value which is "Active = 0"
}
$scope.change = function () {
//Update the data to "Active = 1"
}
I tried using onbeforeunload and onunload but it's not working when I directly close the browser. This is working when I only refresh the browser:
window.onbeforeunload = $scope.default();
I'm using the latest Chrome and Mozilla. I also want to know the limitation of window.onbeforeunload since my page can access using mobile does this will still trigger my function when it directly closed browser on mobile.
Thanks guys, I found a solution on my question. I used the below codes:
window.onbeforeunload = function (e) {
e.returnValue = true;
$scope.default();
return 'onbeforeunload';
}
This solution is to make onbeforeunload work on Chrome. However I want to know if this will still run the function if I run my page to mobile and to other browser/s.

How to Fire Angularjs Event when close browser or window?

I want to clear local storage values when user close browser or window tab using in angularjs. I tried the following code.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
alert("exit");
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
In the above code it asks the confirmation alert messages when refresh the page and also close the page. But i want to fire angularjs event when close the browser/Window Tab only no need to ask the confirmation messages.
In the last project I worked on, I used the following code:
$window.onbeforeunload = function (event) {
if (self.form.$dirty) {
return 'You have made changes, but you did not save them yet.\nLeaving the page will revert all changes.';
}
}
First it performs a check to see if the data in the form has been changed. If so, when the user tries to close the window or go to another url, a popup will be shown stating that there are unsaved changes.
So in this event you have access to the controller, so all angular events should be able to fire.
This one worked for me, but you need to pay attention that the custom message doesn't work in most of the browsers, (such as chrome, IE, firefox).
window.onbeforeunload = () => {
return 'Are you sure you want to leave without saving?';
}
This will fired when the user refresh or close the tab or window, with the browser default message.
i have tried this code, it works for me!
window.onbeforeunload = close;
function close(){
// do something...
localStorage.clear();
sessionStorage.clear();
return null;
}

JavaScript - bfcache/pageshow event - event.persisted always set to false?

In a standard Java / SpringMVC / JSP / jQuery web-app, I'm trying to detect a "Back" (or history.go(-1)) event, in order to refresh (AJAX) a summary component/panel content when I return to a page (where we can change the backend data that is displayed by the summary component).
I tried the following in JavaScript (following some posts on StackExchange re how to achieve this):
<script type="text/javascript">
$(document).ready(function() {
window.onpageshow = function(event) {
console.log("Event:");
console.dir(event);
if (event.persisted) {
alert("non-jQuery - back to page - loaded from bfcache");
} else {
alert("non-jQuery - loaded page from server");
}
};
$(window).on("pageshow", function(event){
console.log("Event:");
console.dir(event);
if (event.originalEvent.persisted) {
alert("jquery - back to page - loaded from bfcache");
} else {
alert("jquery - loaded page from server");
}
});
});
</script>
I am running OpenSUSE Linux and have tried this with FireFox and Chrome (latest versions), but every time the event's persisted attribute is set to false (I can see this in the JavaScript console and by the alerts that pop-up from the above code). By every time, I mean, regardless of whether it was loaded from the server or shown again via the Back button (or a 'Back' link).
My intention was to make an AJAX call to reload the summary component/panel with the updated data from the server if the page was showing via the Back button or history.go(-1) call.
I also tried setting an unload handler (that does nothing) to prevent the page from being put into the bfcache but it still seems to be showing a bf-cached version and the event.persisted (or event.originalEvent.persisted) is set to false.
Is this property managed correctly on Linux? Am I doing something stupid in my code? Any help or ideas would be much appreciated, thanks!
I have found hidden input buttons are not a reliable solution since they may hold the wrong value when the user navigates back to the page and then hits refresh. Some browsers (Firefox) retain input values on refresh so every time the user hits refresh it will refresh again since the input button holds the wrong value. This is a typical scenario for forums (user views a topic, hits the back button to go back to the list of topics, and may continue to hit refresh to check if there are new topics).
As noted by Grégoire Clermont, event.persisted is buggy in chrome (and IE) and this still hasn't been fixed for either browser as of Feb 2017. The good news is you can rely on window.performance.navigation.type == 2 for chrome and IE. Ironically Firefox is unreliable for the latter but it shouldn't matter since it is reliable for event.persisted. The following code worked for me:
if (document.addEventListener) {
window.addEventListener('pageshow', function (event) {
if (event.persisted || window.performance &&
window.performance.navigation.type == 2)
{
location.reload();
}
},
false);
}
Update 2022:
Because window.performance.navigation.type is deprecated (ref: MDN), I updated the code to do the same thing:
if (document.addEventListener) {
window.addEventListener('pageshow', function (event) {
if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
location.reload();
}
},
false);
}
This appears to be a bug in Chrome (also present in IE11).
I have found the following workaround:
<input type="hidden" id="cacheTest"></input>
<script>
var input = document.querySelector('#cacheTest')
if (input.value === "") {
// the page has been loaded from the server,
// equivalent of persisted == false
}
else {
// the page has been loaded from the cache,
// equivalent of persisted == true
}
// change the input value so that we can detect
// if the page is reloaded from cache later
input.value = "some value"
</script>
This exploits the fact that in most browsers, when the page is loaded from the cache, form fields values are also conserved.
I know this is a bit late but this works for me:
window.onpageshow = function(e) {
if (e.persisted) {
alert("Page shown");
window.location.reload();
}
};
I don't think you need it in the document ready function, just use vanilla as above.

Categories