How to detect refresh action(by clicking refresh icon in browser)? - javascript

I want to restrict the page refresh only when we doing this by clicking the refresh icon at the top left side of the browser.
I have tried more available options like,
'beforeunload' event, which can fire on each time of unloading(refresh, navigation, close) the browser.
Inside the event, I have tried 'window.performance.navigation.type' and window. performance.getEntrieaByType('navigation').map(nav=>nav.type) options. But both aren't giving the correct result. On each actions like "refresh", "navigation" and "close" getting the same result. Also sometimes getting different result. So I amn't trusting the options.
So can anyone help me to get the correct option to detect the refresh action done by browser refresh icon?
I am using react application.

window.onbeforeunload = ()=>{
localStorage.setItem("unload",Date.now());
}
useEffect(){
let last_unload = localStorage.getItem('unload');
let decided_time = 1000;
if(last_unload){
// means the user have closed the page
if(Date.now() - parseInt(last_unload,10) <= 1000)
{
// this is a refresh
console.log('refresh handling code')
}else{
// It's a new session, means user came to page, closed the browser, now came back after a long time
}
}
}
Generally the answer from here
should work but because you are stating that window.performance is ambiguous in your case try something like this. Let me know if this helps!

Related

Make jQuery prevent going back on android

I have a simple pop-up contact form script written:
$(document).ready(function(){
var popupButton = $("#contact-popup-button");
var popupBox = $("#pop-up-contact");
var popupBg = $("#pop-up-close-background");
popupButton.on("click", function(){
popupBox.addClass("slide-out");
popupBg.fadeIn(200);
});
popupBg.on("click", function(){
popupBox.removeClass("slide-out");
popupBg.fadeOut(100);
});
Basically when a button is clicked, a div appears and the space behind it gets foggy. If you press the space around the appeared div, it will dissapear.
Now for mobile devices, I'd like there also to be an option to make the div dissapear on clicking the back button. Unfortunately, I can not get it to work in practice at all.
I have tried these answers:
handling back button in android from jquery
Take control of hardware back button jquery mobile
But both seem to fail in this task, and the others use plugins, which I'd like to avoid.
Tested on LG G2 Mini and Sony Xperia Z1
One approach would be to use the HTML5 History API.
When opening the popup you can push a state to the history stack before opening the popup:
history.pushState({popupOpen: false}, "My title", "index.html");
This method automatically updates the page title (which is currently ignored in most browser implementations) and the last part of the url, that will be displayed in the browser bar. In most cases, you can enter your filename here. The first argument is an object containing the data you can access later when popping a state.
As soon as you have pushed a state to the history stack, when pressing the back key, the browser does not return to the last page as usual, but pops the last state on the stack. This applies for all browsers though, if you want the functionality for mobile browsers only, you have to do a browser check before calling history.pushState.
To correctly handle the back event, you need to subscribe to the popstate-Event. This can be done with the following code:
window.addEventListener("popstate", function(event) {
var data = event.state;
if(data.popupOpen === false) {
popupBg.trigger('click');
}
});
You register an event listener that fires as soon as the user navigates back. In the event.state variable the data you passed in when pushing the state can be accessed again.
Good luck!

Unexpected performace.navigation.type onbeforeunload

I'm trying to handle some logic on before unload and I don't want that logic to run if the user is reloading the page or going back.
I've set up something like this.
window.onbeforeunload = function(e) {
if(window.event && window.event.clientX){ //IE
//some logic
} else if (e.currentTarget.performance.navigation.type === e.currentTarget.performance.navigation.TYPE_RELOAD) {
// another logic
} else if(e.currentTarget.performance.navigation.type === e.currentTarget.performance.navigation.TYPE_BACK_FORWARD){
// yet another logic
}
}
I have other code to handle refresh and such from keyboard input that all seems to be working ok. Right now I'm concerned with this piece of code. For some reason on the first reload or back button the navigation.type comes back as 0, but after that all other reloads or back buttons populate the correct value in navigation.type. Even in IE on the first reload something is not being set correctly (not sure if its the mouse location or what yet). What could be causing something like this?
First of all, I think what you wanted to write was e.currentTarget.performance.navigation.type (not e.current.performance.navigation.type), which is the same as writing window.performance.navigation.type. This variable tells you how this page was navigated to, not the type of navigation that the page is exiting through.
Why you get performance.navigation.type as 0 (performance.navigation.TYPE_NAVIGATE) the first time is that the page was loaded by direct navigation that first time. Subsequent reloads will set performance.navigation.type to 1 (performance.navigation.TYPE_RELOAD) because the page is now loaded by reloading. So, you are getting the method that was used to load the page, not the method that the user is using to exit the page.

How to disable browser feature

I am developing a project where user gets a conformation page. I want user not to click back or close tab or reload.
Now either I need to disable the browser features or get back button,tab close event, or reload event to java script so that I could take the needed steps to prevent my data to get lost.
I have used this:
window.onbeforeunload = function()
{
return "Try This";
};
But this get called even when I click a button that redirects the page.
If you just want to have the alert, understanding that the user is ultimately in control and can bypass your alert, then do what you're doing but use a flag that disables it when you're navigating and don't want the alert. E.g.:
var warnWhenLeaving = true;
window.onbeforeunload = function() {
if (warnWhenLeaving) {
return "your message here";
}
};
then in a click handler on the link/button/whatever that moves the user on that you don't want this to pop up on:
warnWhenLeaving = false;
In a comment you asked:
can i know that what user has clicked when alert is generated with this function. That is can i know what user has clicked (leave this page/stay on page)
The answer is: Sort of, but not really; you're almost certainly better off not trying to.
But: If you see your onbeforeunload function run, then you know the user is leaving the page and the browser is likely to show them your message. The browsers I'm familiar with handle the popup like an alert: All JavaScript code on the page is blocked while the popup is there. So if you schedule a callback via setTimeout, you won't get the callback if they leave and you will if they stay:
window.onbeforeunload = function() {
if (warnWhenLeaving) {
setTimeout(function() {
display("You stayed, yay!");
}, 0);
return "No, don't go!";
}
};
Live Example
So in theory, if you get the callback, they stayed; if you see an unload event, they left. (Note that there are very few things you can do in an unload event.)
I've tried that on current Chrome, current Firefox, IE8, and IE11: It works on all of those. Whether it will work in the next release of any of them is anybody's guess. Whether it works reliably on mobile browsers is something you'd have to test, and again could change.

If confirm message idle force to close browser in javascript

i have a confirm message which is showing when page is idle for some time in javascript . The confirm pop up came once the session time out. At that time if we give any response to the confirmation pop up it will do the corresponding process. My requirement is if we are not giving any response means i need to force the browser to close.. can anybody help me on this?
window.setTimeout('checkIfContinue()', 5*1000);
var sFlag=0;
function checkIfContinue()
{
window.setTimeout('idleTime()', 5*1000);
if(sFlag == 0)
{
sFlag = 1;
if(confirm("Your Session Expired!. Do you wish to continue?"))
{
window.setTimeout('checkIfContinue()', 5*1000); //start the timer again
sFlag = 0;
}
else
{
// logout
}
}
}
This is the query which i used to call the pop up after session time out. I need to close the browser when no responses given to the responses..
I believe that in this case you'll need to use some other than system dialog.
E.g. showing a DIV with the question and buttons, so you'll be able to close the window even with opened "dialog".
In jquery, there are plugins for this kind of dialogs like Jquery UI, or select on of theese:
http://choosedaily.com/1178/15-jquery-popup-modal-dialog-plugins-tutorials/
Also remember, that the browser window can be closed by script only when it was opened by the script. Otherwise the function window.Close(); will ask the user about closing.

Alerts when navigating away from a web page

When I try to close my Google docs tab with unsaved changes, this is what I get in my browser (FF 3.5).
Are you sure you want to navigate away
from this page?
You have unsaved changes in this
document. Click Cancel now, then
'Save' to save them. Click OK now to
discard them.
Press OK to continue, or Cancel to
stay on the current page.
My question is whether such alerts are part of the web app (gdocs for eg.) or are they given out by the browser? If latter, how is this done?
By the browser. It's the beforeunload event handler that returns the customized text of the dialog, which is only the middle of the three paragraphs - the other two paragraphs as well as the text of the buttons cannot be customized or otherwise changed.
window.onbeforeunload = function(){ return 'Testing...' }
// OR
var unloadListener = function(){ return 'Testing...' };
window.addEventListener('beforeunload', unloadListener);
Will yield a dialog that says
Are you sure you want to navigate away from this page?
Testing...
Press OK to continue, or Cancel to stay on the current page.
You can nullify this by setting the handler to null
window.onbeforeunload = null;
// OR
window.removeEventListener('beforeunload', unloadListener);
The alerts are part of the web application. View the source code and look at the javascript.

Categories