php/javascript prevent page reload/refresh - javascript

In my project i have a php page where i whant that in case of browser reload, or F5 the page redirect to another one.
I have insert this code:
<script type="text/javascript">
window.onbeforeunload = function() {
window.location.href = "../index.html";
}
</script>
If instead of window.location.href instruction i insert an alert("test"); the code run, but with my code in case of refresh the page cannot redirect to index.html. Why?

You can capture the F5 or CTRL+R keypresses and handle events before a redirect. Although changing any default browser behavior may be considered evil and more of an annoyance by your website users.
Here i have provided an example function to handle redirecting the user when they try to refresh the page. http://jsfiddle.net/dQEeW/
The heart of it and what handles the location change is this event binding.
$(document).bind('keydown', function( event ){
if( event !== undefined ) {
if( (event.keyCode == 82 &&
event.ctrlKey
) || (event.keyCode == 116)
) {
event.keyCode = 0;
if(destination) window.location.href = destination;
return !destination; //false if destination was set true otherwise.
}
}
});
The function was based on another SO answer but I have limited it to only handle F5 and expanded it a bit to handle CTRL+R. You can only limit the keyboard driven refreshes though.
Pulling from yet another SO answer you may want to capture page unloads and return a string, to warn the users they are trying to do something it hasn't been designed to do.
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
That should give you the opportunity to address the reason they want to leave and a chance for them to cancel it.

Related

Prevent user to leave page without the confirmation

I have found on StackOverflow this script that handles the issue when a user wants to leave the page, to ask him before doing it.
ISSUE
It is working fine (even though there is probably a much better solution) but I have realized that it is causing one "bug". When a user sends data from the form and the script asks him does he want to leave the page (because of the redirect) it still sends data. So, even if the user clicks on "Cancel" it will still proceed to the store() method and if the user adds something more and sends again the data I get duplicates. Is there a way to include "stop propagation" in this script?
CODE
window.onbeforeunload = function () {
return 'Are you sure you want to close this website?';
};
Additional question
Since this script is running with the Laravel Livewire, every time I click on any button related to the livewire (which won't redirect the user to the other page) script prompts the popup to ask if the user is sure he wants to leave the page. Is there any workaround (if you need some other code, write a comment because I am not sure which part could help you at all :) ) for this issue?
Try this:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
</script>
Here is a working jsFiddle

Detect if page is load from back button [duplicate]

This question already has answers here:
How do I detect if a user has got to a page using the back button?
(12 answers)
Closed 10 days ago.
Is there any way to detect if current page came from back button?
I want to load data from cookie only if current page came from back button.
Note: This is reported to no longer work in the latest versions of Chrome.
When a user goes back a page, any visible form data is preserved, while any JavaScript variables are reset. I say 'visible' form data, as hidden fields seem not to be preserved, but invisible inputs are.
You can use this to your advantage in order to detect whether the page was an initial load, or had already been loaded previously such as from a back button click.
Create a invisible input field (not type 'hidden') with a value of '0', and within a DOM ready loader check to see if the value has been set to '1'; if it has you know the page has already been loaded, such as from a back button; if it is still '0' then the page has initially loaded for the first time, set the value to '1'.
Note: This is a bit delicate in the way it works, and probably doesn't work in all browsers; I built it with Chrome in mind.
The DOM needs to be loaded; not all ready functions work. The one
below does, so does the JQuery ready; however (function() { }) in my instance does not.
The Input cannot be of type="hidden". Set style="display:none;"
on the input instead.
.
<input id="backbuttonstate" type="text" value="0" style="display:none;" />
<script>
document.addEventListener('DOMContentLoaded', function () {
var ibackbutton = document.getElementById("backbuttonstate");
if (ibackbutton.value == "0") {
// Page has been loaded for the first time - Set marker
ibackbutton.value = "1";
alert('First time load');
} else {
// Back button has been fired.. Do Something different..
alert('Previously loaded - Returned from Back button');
}
}, false);
</script>
For a simpler check, there're Navigation Timing API Spec (already deprecated, but widely supported) and Navigation Timing Level 2 API Spec (working draft, supported by major browser)
if (window.performance) {
var navEntries = window.performance.getEntriesByType('navigation');
if (navEntries.length > 0 && navEntries[0].type === 'back_forward') {
console.log('As per API lv2, this page is load from back/forward');
} else if (window.performance.navigation
&& window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
console.log('As per API lv1, this page is load from back/forward');
} else {
console.log('This is normal page load');
}
} else {
console.log("Unfortunately, your browser doesn't support this API");
}
if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
$('.formName').get(0).reset();
}
Use pageshow event to detect back or forward buttons:
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
Alert("User clicked on back button!");
}
});
For more details you can check pageshow event in here .
In addition to #Radderz answer, I had to add setTimeout to make their solution work in chrome 83. Otherwise, I would only see 'First time load' alert.
In the HTML:
<input id="backbuttonstate" type="text" value="0" style="display:none;" />
In the script:
document.addEventListener('DOMContentLoaded', function () {
var ibackbutton = document.getElementById("backbuttonstate");
setTimeout(function () {
if (ibackbutton.value == "0") {
// Page has been loaded for the first time - Set marker
ibackbutton.value = "1";
alert('First time load');
} else {
// Back button has been fired.. Do Something different..
alert('Previously loaded - Returned from Back button');
}
}, 200);
}, false);
I think this could be done with sessionStorage if you are working with pages within your project(This does not take external pages into account). Off the top of my head, when you are on your "Main Page" then you click a link and go to the next page.
On that next page, you can set a value in sessionStorage like:
sessionStorage.setItem('doSomething', 'yes');
Then back to your Main page, you can have a condition like:
const sCheckSession = sessionStorage.getItem('doSomething');
if(sCheckSession == 'yes') {
// do something crazy, then reset your reference to no
// so it wont interfere with anything else
sessionStorage.setItem('doSomething', 'no');
}
Basically, you can't because of browser restrictions. HTML5 history API, the onpopstate event will be triggered when navigating to back page. But this will fire even if u use application navigation.
alternative solution refer - How to Detect Browser Back Button event - Cross Browser

Detect if the user arrived to the current page via the browser back button

I have a site where if a user navigates to a certain page then he gets a dialog notification depending on some condition on the page. The user can navigate to other pages from this page and of course can press the back button on those pages to navigate back to this page.
I'd like to detect if the user arrives via the back button to this page, so the dialog notification is not shown again (because the user has already seen it).
Is there a way to detect this reliably?
MDN list of window events
Your best possibility may be window.onpageshow = function(){};
An event handler property for pageshow events on the window.
window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
Input trick is not longer working. Here's the solution I use:
if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
alert('Got here using the browser "Back" or "Forward" button.');
}
The best (although not TREMENDOUSLY reliable) way is to use the Javascript history object. You can look at the history.previous page to see if it's the next in the series. Not a great solution, but maybe the only way to figure it out.
I like use a value in an input field for this:-
<input type="hidden" id="fromHistory" value="" />
<script type="text/javascript">
if (document.getElementById('fromHistory').value == '') {
document.getElementById('fromHistory').value = 'fromHistory');
alert('Arrived here normally');
} else {
console.log('Arrived here from history, e.g. back or forward button');
}
</script>
This works because the browser repopulates the value of the field with the one the javascript puts in there if it navigates back to it from history :-)

Call a function on page refresh using Javascript

function warnuser()
{
return "Don't refresh the page.";
}
window.onbeforeunload = warnuser;
If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not!
I am confused about how to do that.
Thank you
You need to intercept the F5 key press and setup the onbeforeunload handler only in that case:
document.addEventListener('keydown', function(e) {
if(e.which == 116) {
window.onbeforeunload = function() {
window.onbeforeunload = null;
return "Do you really want to refresh the page?";
}
}
}, false);
Demo: http://jsfiddle.net/ejDrq/
Note that this does not work if the user clicks the Refresh button. It is impossible to intercept this.
If you have control of the server side which is hosting the page then you can handle this logically with a semaphore (wiki:semaphore). Basically it is a spinning lock which would be implemented in their server side session. Resetting the page state if they have entered and not exited in a safe manner. Naturally, as with all spinning locks, there would have to be a safe state to clear the lock out.

How to capture when a user is leaving ASP.Net page unexpectedly

I need to prompt a user when they are leaving my ASP.Net page unexpectedly with a message to ask if they are sure they want to leave. A post back or when the save button is clicked should not fire the warning. There are a bunch of articles covering this but I am brand new to this and appear to have got my wires crossed.
The recommended way appears to be to use the window.onbeforeunload event but behaves unexpectedly for me. This is fired when the page loads as opposed to when the page unloads.
<script language="JavaScript" type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
If I use the JQuery implementation it fires when the page unloads but the problem is it fires before the code behind is executed. So I cannot set a variable on the client saying don’t fire the event this time as it is a post back or a Save.
$(window).bind('beforeunload', function () {
return 'Are you sure you want to leave?';
});
Can anyone point me in the correct direction as I know I am making basic mistakes/miss-understanding?
Edit:
So I am nearly there:
var prompt = true;
$('a').live('click', function () {
//if click does not require a prompt set to false
prompt = false;
});
$(window).bind("beforeunload", function () {
if (prompt) {
//reset our prompt variable
prompt = false;
//prompt
return true;
}
})
Except the problem is in the above code I need to be able to differentiate between the clicks but I haven't been able to figure that out yet i.e. I am missing a condition here "//if click does not require a prompt set to false".
Any ideas?
Thanks,
Michael
You can try using this:
$(window).unload(function(){
alert('Message');
});
In case people are interested this is the roundabout solution to my problem. How to tell if a page unload in ASP is a PostBack

Categories

Resources