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.
Related
I'm trying to detect if my current page is loaded from cache or is a fresh copy.
I have the onPageShow callback registered on my body tag.
I can see it being triggered, but I cannot produce a circumstance where the event.persisted is actually true.
I've even put firefox in offline mode and I see the response being fetched from cache on the network tab but event.persisted is still false.
Umm I can confirm var isCached = performance.getEntriesByType("navigation")[0].transferSize === 0; this does work on Chrome. Worth trying out.
Also as other suggested you might wanna look at this example How can I use JavaScript to detect if I am on a cached page
From google books
This works in mozilla perfectly.
Try the below code
<meta http-equiv="Cache-control" content="public">
...
<body onpageshow="onShow(event)" onpagehide="onHide(event)">
<div >
<a href='/new.html' >Next page</a>
</div>
<script>
function onShow(event) {
if (event.persisted) {
alert('Persisted...');
}
}
function onHide(event) {
if(event.persisted) {
alert("Persisted")
}
}
</script>
</body>
Add any code in new.html. Blank page is also fine
Then use the browser back. You'll get the alert persisted
Note:
Use a domain or ngrok . Cache doesn't work in local
Reload wont trigger persisted. I tried only with page show/hide
I'am skipping the alternative answers to find cache or not
IE11 does have window.performance.getEntriesByType('navigation') but doesn't have transferSize. However, it seems to leave out connectEnd if the page comes from browser cache.
Extending on #subhendu-kundu s answer, this should also work on IE11
<script>
window.addEventListener('pageshow', function(event) {
if (window.performance) {
var navEntries = window.performance.getEntriesByType('navigation');
if (navEntries.length > 0 && typeof navEntries[0].transferSize !== 'undefined') {
if (navEntries[0].transferSize === 0) {
// From cache
}
} else if (navEntries.length > 0) {
// IE11 seems to leave this completely if loaded from bfCache
if (!navEntries[0].connectEnd) {
// From cache
}
}
}
});
</script>
I don't know if i understood your question correctly, you want to check if the page that is loaded is from disk/memory cache or a fresh one. Please comment below if i understood it wrong.
I'm trying to detect if my current page is loaded from cache or is a
fresh copy.
For this you can open the developer tools of your browser and check the network tab, if the page is loaded from cache it will show indication (from cache).
Chrome supports this out of the box but for fire fox i think you should install web-developer plugin : https://addons.mozilla.org/en-US/firefox/addon/web-developer/
Well one thing I can suggest to disable the cache in the browser and check the size of the fetched code chunk. For the same you can disable the cache from browser itself..(I am just suggesting my views).
I'm using a simple .html page to redirect someone to page A if they don't have a cookie. If they do have the cookie I want to send them to page B.
The issue I'm having is someone will get redirected to page A, but when they push the back button on page A, the .js isn't executing on my simple .html page and sending them to page B. Instead, the blank .html page is loading and that's it.
//this function fixed Safari
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
window.onunload = function() {}; // this seems to have fixed Firefox
setTimeout(function() {
if (document.cookie.indexOf("visitedinhour=") >= 0) {
// They've been here before.
window.location = 'https://www.google.com';
} else {
// set a new cookie
document.cookie = "visitedinhour=true; max-age=" + 3600;
window.location = 'https://www.bing.com';
}
}, 200);
What I'd like to happen is someone visits my .html page, is redirected to page A, then click the back button, and are redirected to page B.
UPDATE: Firefox seems to work as intended. Chrome and Safari don't. Chrome goes back to the page before my .html page and Safari still loads the blank .html page.
UPDATE 2: Safari is fixed; Chrome isn't working as intended. When on Bing.com and you click the back button the browser goes to the page it was on before my .html page with this code.
This could be a known issue in Firefox.
Try to set an empty function to be called on window.onunload:
window.onunload = function() { };
This is because Firefox (and Safari, and Opera) keeps the website intact. it does not immediately destroy your page to go onto the next one, which results in a much faster and smoother back/forward page transitions for the user.
Update
This should work for Safari (it will force a reload when page is loaded from bfcache):
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
Update 2:
This code should be compatible with all browsers although you may need to use the above snippets too.
window.addEventListener("pageshow", function (event) {
var historyTraversal =
event.persisted ||
(
// Check if performance not undefined (restored from cache)
typeof window.performance != "undefined" &&
// Check if the back button was used
window.performance.navigation.type === 2
);
if (historyTraversal) {
// Handle page restore and reload the page
window.location.reload();
}
});
When using window.onbeforeunload (or $(window).on("beforeunload")), is it possible to display a custom message in that popup?
Maybe a small trick that works on major browsers?
By looking at existing answers I have the feeling this was possible in the past using things like confirm or alert or event.returnValue, but now it seems they are not working anymore.
So, how to display a custom message in the beforeunload popup? Is that even/still possible?
tl;dr - You can't set custom message anymore in most modern browsers
A quick note (since this is an old answer) - these days all major browsers don't support custom message in the beforeunload popup. There is no new way to do this. In case you still do need to support old browsers - you can find the information below.
In order to set a confirmation message before the user is closing the window you can use
jQuery
$(window).bind("beforeunload",function(event) {
return "You have some unsaved changes";
});
Javascript
window.onbeforeunload = function() {
return "Leaving this page will reset the wizard";
};
It's important to notice that you can't put confirm/alert inside beforeunload
A few more notes:
NOT all browsers support this (more info in the Browser compatibility section on MDN)
2. In Firefox you MUST do some real interaction with the page in order for this message to appear to the user.
3. Each browser can add his own text to your message.
Here are the results using the browsers I have access to:
Chrome:
Firefox:
Safari:
IE:
Just to make sure - you need to have jquery included
More information regarding the browsers support and the removal of the custom message:
Chrome removed support for custom message in ver 51
Opera removed support for custom message in ver 38
Firefox removed support for custom message in ver 44.0 (still looking for source for this information)
Safari removed support for custom message in ver 9.1
When using window.onbeforeunload (or $(window).on("beforeonload")), is it possible to display a custom message in that popup?
Not anymore. All major browsers have started ignoring the actual message and just showing their own.
By looking at existing answers I have the feeling this was possible in the past using things like confirm or alert or event.returnValue, but now it seems they are not working anymore.
Correct. A long time ago, you could use confirm or alert, more recently you could return a string from an onbeforeunload handler and that string would be displayed. Now, the content of the string is ignored and it's treated as a flag.
When using jQuery's on, you do indeed have to use returnValue on the original event:
$(window).on("beforeunload", function(e) {
// Your message won't get displayed by modern browsers; the browser's built-in
// one will be instead. But for older browsers, best to include an actual
// message instead of just "x" or similar.
return e.originalEvent.returnValue = "Your message here";
});
or the old-fasioned way:
window.onbeforeunload = function() {
return "Your message here"; // Probably won't be shown, see note above
};
That's all you can do.
As of 2021, for security reasons, it is no longer possible to display a custom message in the beforeunload popup, at least in the main browsers (Chrome, Firefox, Safari, Edge, Opera).
This is no longer possible since:
Chrome: version 51
Firefox: version 44
Safari: version 9
Edge: it has never been possible
Opera: version 38
For details see:
https://www.chromestatus.com/feature/5349061406228480
https://caniuse.com/mdn-api_windoweventhandlers_onbeforeunload_custom_text_support
An alternative approach in order to get a similar result is to catch click events related to links (that would take you away from the current page) and ask for confirmation there. It might be adjusted to include forms submission or perhaps redirections through scripts (that would require to apply a specific class and information in the elements that trigger the redirect).
Here is a working code snippet (based on jQuery) that shows you how you can do it:
Edit: the code snippet here in SO does not work on all browsers, for security reasons (the snippet generates an iframe... and in some browsers "Use of window.confirm is not allowed in different origin-domain iframes"), but the code DOES work, so give it a try!
$('body').on('click', function(e) {
var target, href;
//Identifying target object
target = $(e.target);
//If the target object is a link or is contained in a link we show the confirmation message
if (e.target.tagName === 'A' || target.parents('a').length > 0) {
//Default behavior is prevented (the link doesn't work)
e.preventDefault();
if (window.confirm("Are you really really sure you want to continue?")) {
//Identify link target
if (e.target.tagName === 'A') {
href = target.attr('href');
} else {
href = target.parents('a').first().attr('href');
}
//Redirect
window.location.href = href;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click me and I'll take you home
I just made a div appear that shows a message in the background.
It is behind the modal but this is better then nothing. It is kind of shady but at least you can give your user some info on why you bother her/him not to leave.
constructor($elem)
{
$(window).unbind().bind('beforeunload', (e) => this.beforeUnload(e));
}
beforeUnload(e)
{
$('#leaveWarning').show();
setTimeout(function(){
$('#leaveWarning').hide();
}, 1); // set this to 1ms .. since timers are stopped for this modal,
// the message will disappear right after the user clicked one of the options
return "This message is not relevant in most modern browsers.";
}
Here is a working Fiddle https://jsfiddle.net/sy3fda05/2/
You can't set a custom message on a modern browser instead you can use of default alert function.
checkout browser compatibility
Try this code for all all browsers supported
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?';
};
All the above doesn't work in chrome at least it need to add return false otherwise nothing happen.
window.onbeforeunload = function(e) {
$('#leaveWarning').show();
// the timer is only to let the message box disappear after the user
// decides to stay on this page
// set this to 1ms .. since timers are stopped for this modal
setTimeout(function() {
$('#leaveWarning').hide();
}, 1);
//
return false;
return "This message is not relevant in most modern browsers.";
}
I have the following code in my page to submit the form on the page automatically when the DOM is ready:
$(function () {
$('form').submit();
});
However, on the next page if the user clicks back on their browser it goes back to the page before this one rather than the page with this code on (with Chrome/IE anyway). i.e. the page with the form on is missing in the browser history.
This is great, although I wondered is this something all modern browsers now do? I am looking for an answer that cites official sources such as from internet standards documents or from browser vendors that state the mechanism they have implemented.
This appears to only happen if I call the submit() function in the DOM ready or Window load events.
e.g. this code will show the form page in browser history after the page is clicked (back/forward):-
document.addEventListener('click', function () { document.forms[0].submit(); }, false);
the following snippets won't:-
document.addEventListener('DOMContentLoaded', function () { document.forms[0].submit(); }, false);
window.addEventListener('load', function() { document.forms[0].submit(); }, false);
window.onload = function () { document.forms[0].submit(); };
I've dealt with this before. I did not want the back button to take
the user back to previous page. Using onbeforeunload solved the
issue for me...
But your issue is related to the following concepts
Browsing Context
Session History
Replacement Enabled (flag)
A "Browsing Context" is an environment in which "Document" objects
are presented to the user.
The sequence of "Document"s in a "Browsing Context" is its "Session History". The
"Session History" lists these "Document"s as flat entries.
"Replacement Enabled" comes into effect when we propagate from one "Document" to another in the "Session History". If the traversal was initiated with "Replacement Enabled", the entry immediately before the specified entry (in the "Session History") is removed.
Note A tab or window in a Web browser typically contains a browsing context, as does an iframe or frames in a frameset.
Logically thinking, by calling any of these
document.addEventListener( 'DOMContentLoaded', function() {document.forms[0].submit();}, false );
window.addEventListener( 'load', function() {document.forms[0].submit();}, false );
window.onload = function() {document.forms[0].submit();};
you are suggesting the browser to perform #3, because what those calls mean
is that propagate away from the page as soon as it loads. Even to me that code is
obviously :) asking to be cleared off from the "Session History".
Further reading...
onbeforeunload
browsers
browsing-context
unloading-documents
replacement-enabled
Since this code leaves the page in the history when responding to the click event:-
document.addEventListener('click', function () { document.forms[0].submit(); }, false);
and the following pieces of code do not leave the page in history (DOMContentLoaded, and window onload events):-
document.addEventListener('DOMContentLoaded', function () { document.forms[0].submit(); }, false);
window.addEventListener('load', function() { document.forms[0].submit(); }, false);
window.onload = function () { document.forms[0].submit(); };
it can be assumed that modern browsers do not record a navigation history for page navigation that occurs within the window load or document ready handlers.
When the user hits the back button, the browser shows the cached copy of the page. Form submit doesn't cache the page therefore it doesn't show up in your history.
Yes, redirecting from an onload event handler causes the new URL to replace the one you leave in the history (and thus doesn't add a useless entry). But that's not the only trigger for that replacement, it may also be caused by any location change occurring fast enough, this delay being designed to avoid polluting the history in case of JavaScript based re-directions.
It is very hard to find any specification on that topic but on Firefox this delay seems to be 15 seconds. Here's a mention of this delay in bugzilla from one of the moz developers :
Mozilla uses a threshold of 15 seconds to decide if a page should
stay in history or not. If a site uses and
redirects to another site with in 15 seconds OR redirects to another
page in onLoadHandler() etc ..., the redirected page will replace
(and thereby eliminating) the redirecting page from history. If the
redirection happens after 15 seconds, the redirecting page stays in
history.
One may argue about the
time limit. But this is just something we thought was a reasonable number
Got an issue with safari loading old youtube videos when back button is clicked. I have tried adding onunload="" (mentioned here Preventing cache on back-button in Safari 5) to the body tag but it doesn't work in this case.
Is there any way to prevent safari loading from cache on a certain page?
Your problem is caused by back-forward cache. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.
When page is loaded for bfcache onload event wont be triggered. Instead you can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.
Kludgish solution is to force a reload when page is loaded from bfcache.
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
If you are using jQuery then do:
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
All of those answer are a bit of the hack. In modern browsers (safari) only on onpageshow solution work,
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
but on slow devices sometimes you will see for a split second previous cached view before it will be reloaded. Proper way to deal with this problem is to set properly Cache-Control on the server response to one bellow
'Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store'
Yes the Safari browser does not handle back/foreward button cache the same like Firefox and Chrome does. Specially iframes like vimeo or youtube videos are cached hardly although there is a new iframe.src.
I found three 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 or reload only the cached iframes by replacing the src
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
$('iframe').attr('src', function (i, val) { return val; }); // reload only iframes
}
2. reload whole page if page is cached
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
3. remove the page from history so users can't visit the page again by back/forward buttons
$(function () {
//replace() does not keep the originating page in the session history,
document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
});
You can use an anchor, and watch the value of the document's location href;
Start off with http://acme.co/, append something to the location, like '#b';
So, now your URL is http://acme.co/#b, when a person hits the back button, it goes back to http://acme.co, and the interval check function sees the lack of the hash tag we set, clears the interval, and loads the referring URL with a time-stamp appended to it.
There are some side-effects, but I'll leave you to figure those out ;)
<script>
document.location.hash = "#b";
var referrer = document.referrer;
// setup an interval to watch for the removal of the hash tag
var hashcheck = setInterval(function(){
if(document.location.hash!="#b") {
// clear the interval
clearInterval(hashCheck);
var ticks = new Date().getTime();
// load the referring page with a timestamp at the end to avoid caching
document.location.href.replace(referrer+'?'+ticks);
}
},100);
</script>
This is untested but it should work with minimal tweaking.
The behavior is related to Safari's Back/Forward cache. You can learn about it on the relevant Apple documentation: http://web.archive.org/web/20070612072521/http://developer.apple.com/internet/safari/faq.html#anchor5
Apple's own fix suggestion is to add an empty iframe on your page:
<iframe style="height:0px;width:0px;visibility:hidden" src="about:blank">
this frame prevents back forward cache
</iframe>
(The previous accepted answer seems valid too, just wanted to chip in documentation and another potential fix)
I had the same issue with using 3 different anchor links to the next page. When coming back from the next page and choosing a different anchor the link did not change.
so I had
House 1
View House 2
View House 3
Changed to
House 1
View House 2
View House 3
Also used for safety:
// Javascript
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
// JQuery
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
None of the solutions found online to unload, reload and reload(true) singularily didn't work. Hope this helps someone with the same situation.
First of all insert field in your code:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
then run jQuery:
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();
}
});
There are many ways to disable the bfcache. The easiest one is to set an 'unload' handler. I think it was a huge mistake to make 'unload' and 'beforeunload' handlers disable the bfcache, but that's what they did (if you want to have one of those handlers and still make the bfcache work, you can remove the beforeunload handler inside the beforeunload handler).
window.addEventListener('unload', function() {})
Read more here:
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching