Detect if page is load from back button [duplicate] - javascript

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

Related

Prevent back button from going back to previous page for an ID

Using the following function to prevent users from going back to previous page if the page they are on currently has the id #home. But this function doesn't even fire off. No alerts. Nothing wrong with the link to script file as I have other scripts running fine on that file.
document.addEventListener("backbutton", function (e) {
alert("Back button pressed");
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
var activePageId = activePage[0].id;
alert(activePageId);
if (activePageId == 'home') {
e.preventDefault();
}
}, false);
Unless you have created a custom event there is no onbackbutton event I know of. You are after onbeforeunload
Clients don't like it when you block navigation. You should consider other solutions to you problem rather than block navigation. Sure as .... the next thing the client will do is close the tab and a good chance you will never see a session with that client again.

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 :-)

How to refresh page on back button click?

I use .htaccess to route all of my traffic to a single index.php file. The code below to directs traffic, but for some reason it doesn't work with the back button. I don't know what to do to get the back button working. I've tried a variety of things and googled quite a bit and none of it has worked so I'm hoping someone here can help!
<?php
if(isset($_GET['parameters'])) {
if($_GET['parameters'] == "repair")
include 'repair.html';
else if($_GET['parameters'] == "training")
include 'training.html';
else if($_GET['parameters'] == "products")
include 'products.html';
else if($_GET['parameters'] == "about")
include 'about.html';
else if($_GET['parameters'] == "employees")
include 'employees.html';
else if($_GET['parameters'] == "training")
include 'training.html';
else if($_GET['parameters'] == "newaccount")
include 'newaccount.html';
else if($_GET['parameters'] == "contact")
include 'contact.html';
else if($_GET['parameters'] == "recommended")
include 'recommended.html';
else if($_GET['parameters'] == "careers")
include 'careers.html';
else
include 'home.html';
}
else
include 'home.html';
?>
So far I've tried and failed to use: window.onbeforeunload
body onunload=""
There has got to be a way to onunload=location.reload() or something! Somehow has to know the syntax!!
Try this... not tested. I hope it will work for you.
Make a new php file. You can use the back and forward buttons and the number/timestamp on the page always updates.
<?php
header("Cache-Control: no-store, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo time();
?>
aaaaaaaaaaaaa
Or
found another solution
The onload event should be fired when the user hits the back button. Elements not created via JavaScript will retain their values. I suggest keeping a backup of the data used in dynamically created element within an INPUT TYPE="hidden" set to display:none then onload using the value of the input to rebuild the dynamic elements to the way they were.
<input type="hidden" id="refreshed" value="no">
<script type="text/javascript">
onload=function(){
var e=document.getElementById("refreshed");
if(e.value=="no")e.value="yes";
else{e.value="no";location.reload();}
}
A more recent solution is using the The PerformanceNavigation interface:
if(!!window.performance && window.performance.navigation.type === 2)
{
console.log('Reloading');
window.location.reload();
}
Where the value 2 means "The page was accessed by navigating into the history".
View browser support here:
http://caniuse.com/#search=Navigation%20Timing%20API
Reload the site when reached via browsers back button
The hidden input solution wasn't working for me in Safari. The solution below works, and came from here.
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
I found two ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1
1. Detect if user is using the back/foreward button, then reload whole page
if (!!window.performance && window.performance.navigation.type === 2) {
// value 2 means "The page was accessed by navigating into the history"
console.log('Reloading');
window.location.reload(); // reload whole page
}
2. reload whole page if page is cached
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
This simple solution posted here Force page refresh on back button worked ...
I've tried to force a page to be downloaded again by browser when user clicks back button, but nothing worked. I appears that modern browsers have separate cache for pages, which stores complete state of a page (including JavaScript generated DOM elements), so when users presses back button, previous page is shown instantly in state the user has left it. If you want to force browser to reload page on back button, add onunload="" to your (X)HTML body element:
<body onunload="">
This disables special cache and forces page reload when user presses
back button. Think twice before you use it. Fact of needing such
solution is a hint your site navigation concept is flawed.
did you try something like this? not tested...
$(document).ready(function(){
$('.ajaxAnchor').on('click', function (event){
event.preventDefault();
var url = $(this).attr('href');
$.get(url, function(data) {
$('section.center').html(data);
var shortened = url.substring(0,url.length - 5);
window.location.hash = shortened;
});
});
});
You can use the following to refresh the page by clicking the back button:
window.addEventListener('popstate', () => {
location.reload();
}, false);
First of all insert field in your code:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
then run jQuery:
<script type="text/javascript">
jQuery(document).ready(function()
{
var d = new Date();
d = d.getTime();
if (jQuery('#reloadValue').val().length === 0)
{
jQuery('#reloadValue').val(d);
jQuery('body').show();
}
else
{
jQuery('#reloadValue').val('');
location.reload();
}
});
window.onbeforeunload = function() { redirect(window.history.back(1)); };
Ahem u_u
As i've stated the back button is for every one of us a pain in some place... that said...
As long as you load the page normally it makes a lot of trouble... for a standard "site" it will not change that much... however i think you can make something like this
The user access everytime to your page .php that choose what to load. You can try to work a little with cache (to not cache page) and maybe expire date.
But the long term solution will be put a code on "onload" event to fetch the data trought Ajax, this way you can (with Javascript) run the code you want, and example refresh the page.

Disable IE back Button

I have a application where i have disabled the back button of IE8 by using the following code.
window.history.forward();
function noBack() {
window.history.forward();
}
I know this code takes the page back and again moves the page forward. i have called a function onload of the page which makes a textbox read only. i have used the following code to make it read only.
$("#IDofTheTextBox").attr('readonly',true);
but if i select the textbox and try to edit by pressing "BackSpace" button, IE back button is getting invoked and the textbox which was readonly is not readonly anymore. Can anyone help me how to solve this issue?
The answer is simply "NO"
If you're trying to prevent the user from losing their work, try something like:
window.onbeforeunload = function() { return "Are you sure want to leave this page?."; };
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
You add the above javascript functions in the js file and onload call the function changeHashOnLoad().
its working fine in IE8. i just tested it.
I dont know what your page is trying to do... but this is what we do:
We have an assessment where we do not want the browser buttons enabled... because we run ajax/logic when the user hits next/back etc (to determine what to display next based on their inputs). Back and forward buttons can muddy that process up.
So..... we have users open our assessments in A NEW WINDOW so the back button is already disabled...(there is no prior history in a new window). Then, Our next/back buttons use window.location.replace(url); This will prevent a history item from being created. Therefore, the back/forward buttons are never enabled and they must use the next/prev buttons to navigate our tool.
I would not try to muck with the buttons outside of something like the example I provided.

JavaScript interrupt event

Here is the situation :
If I am in page-1 now I am clicking a link from page-1 to navigate to page-2. Before page-2 is loaded I am hitting escape so that still I am staying in page-1.
At that point I want to track that event.
Is there any JavaScript event so that I can track the above scenario?
More Info :
To avoid concurrent request to the "page-2", when the user clicks a link from page-1 I am redirecting to page-2 and disabling the link (to avoid multiple request to "page-2). At this point when we hit Esc and abort loading page-2, I need to enable the link again in page-1.
I tried using this code:
<html>
<head>
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event; //IE Compatibility
alert(e.keyCode);
}
</script>
</head>
<body>
Stack Overflow
</body>
</html>
It detects any key pressed while you're on the page. Once you click on the SO link and hit escape, nothing happens. The browser is already receiving a response from the SO server and is starting to process it, this page has already been "left", despite appearances when you see "Waiting for http://stackoverflow.com" in your browser's status bar.
Your idea of handling this event is plain wrong. Blocking the button is required to make the user unable to do double post data. However, the request is sent instantaneously(!) after the click on the link.
So, if you click the link once, stop the page, then click second time - it will submit it twice, and that is not what is intended to happen.
Two events are triggered when the page unloads.
window.onUnload
window.onBeforeUnload
You can use these events to cancel the unload of the page, however after that, there page is considered done.
What you can do is make the page wait 5 secs or so before going to the new page:
eg:
window.onunload = (function() {
var time = new Date();
var cancel = false;
window.onkeypress = function (e) {
if ((e || window.event).keyCode == 27) cancel = true;
};
while(time > new Date() - 5000) {
if (cancel) return false;
}
});
In fact that may cause some browsers to hang since you're taking up all process time given to the JS script. ie: in the while block.
You could probably avoid that by doing a blocking function call, that isn't so process intensive, like one that is bound by network latency. eg: XMLHttpRequest() etc. I don't think calls that are queued such as setTimeout() will work here, as they don't block.
Since the <a href> tag tells the browser to move to another page, it's up to it to decide if it will still have your script running. If I were it, I wouldn't listen.
If you want to override that, I guess you should tell the browser not to listen to that particular onClick event, and put a callback in place that loads the target page in the background. This assures your page is still active. After the target page has loaded (by your script), you could kindly ask the browser to update itself with the received content.
So that's the theory. I have no idea if the DOM lets you just override the content of a loaded page, but I guess it does.

Categories

Resources