I am curious if there is a way to detect the browser refresh event in javascript specifically. We are using the jQuery.address plugin to provide forward and back button functionality to AJAX functions. The problem I am facing is that this plugin does not seem to detect if the user has refreshed the page.
This code is executed each time the user moves forward or back in the browser history. I would also like it to exexute when the user refreshes.
$.address.init(function(event) {
}).change(function(event) {
SummaryDiv.SwapPanels(newPanelID);
}
Any ideas?
Along these lines, I had a page whose behavior I didn't want to repeat if refreshed, so I changed the hash programmatically as described in this answer.
checkRefresh: function() {
if (document.location.hash === '#visited') {
console.log('Refreshed');
return true;
} else {
document.location.hash = 'visited';
return false;
}
}
UPDATE
I found that at least Mobile Safari would ignore the hash if the refresh occurred automatically (e.g. page data expunged from cache before being viewed again). I ended up using a more complex solution described here.
A naive attempt of mine would be to simply store the current state into some cookie after each change and simply load them again on each page load.
Found this on the web for you...
Has both a javascript clever method along with a cookies method.
http://www.tedpavlic.com/post_detect_refresh_with_javascript.php
On a page refresh, the javascript is also reloaded. So couldn't you specify what you want to happen directly in jQuery's ready method?
I was able to force the change event code to run on refresh by
window.onload = $.address.update(function(){
...
})
In javascript you can do this:
page1.html
<script>
localStorage.removeItem('setear1')
</script>
page2.html
<script>
addEventListener('DOMContentLoaded', () => {
let vengoDeLaPaginaAnterior = localStorage.getItem('setear1')
if (vengoDeLaPaginaAnterior === null) {
localStorage.setItem('setear1', 1)
} else {
document.location.href = 'page1.html'
}
})
</script>
then: if user refresh page, return to previus page.
Related
My Wordpress site has conflicting plugins. So when I click a page in the menu, it get stuck but fixes when the page has been re-loaded.
My approach is to auto refresh the page (the menu link that has been clicked) so the page will properly load.
After searching for couple of days, I haven't found the exact way to do it.
I use
location.reload(true);
but it keeps reloading. I tried also
location.reload(true);
window.stop();
but it stops loading before it completes the page load to 100%.
So my question is, can we add a loop to stop the reload?
example…
after 2 reloads, the js code will stop
Hopefully someone can help me. Thanks!
Try this piece of JavaScript, it stores the reload count in LocalStorage:
if(typeof(localStorage.getItem('rlcount')) == 'undefined'){
localStorage.setItem('rlcount', 0);
}
if(localStorage.getItem('rlcount') < 2){
localStorage.setItem('rlcount', localStorage.getItem('rlcount') + 1);
window.location.reload();
}else{
localStorage.removeItem('rlcount');
}
However, you should note that reloading a page is not a good fix for your bug, you should find the root cause.
While I would encourage you to try to fix the root problem causing the behavior you described, you could do something like the following to reload the page twice:
window.onload = function() {
if (!window.location.hash) {
window.location = window.location + '#loadedOnce';
alert("Reloading first time...");
window.location.reload();
} else if (window.location.hash === "#loadedOnce") {
window.location = window.location.hash.replace("#loadedOnce", "#loadedTwice");
alert("Reloading second time...");
window.location.reload();
} else if (window.location.hash === "#loadedTwice") {
// Page reloaded twice, do whatever...
}
}
This makes use of a hash in the URL, so it does not require using the localStorage API (although that is a perfectly fine approach too if the browser supports it, and might work better if you already have hashes in the URL).
Thank you for taking time to answer my question guys…
I found a simple way (not a loop though). Not sure if this is ok but it's working when I added "return".
location.reload();
return;
When adding this command. it simply reloaded once.
The context is a game. When user refreshes his page (F5 or ctrl+R), I want the page to be redirect to gameOver.php page.
Can this be done in pure JS ?
One way to go about is to use a cookie variable as a counter. Every time the user starts the game, you set it to 1 and then increment it on every page load. On page load, you can check the variable's value and redirect using
window.location = 'gameOver.php'
or you can use beforeunload event.
$(window).on("beforeunload", function() {
//your redirect code logic here
})
You can do easily with this code when you want solve with pure javascript:
window.addEventListener("beforeunload", function (e) {
window.location = "gameOver.php";
});
Or you can do with jQuery like below:
$(window).on("beforeunload", function() {
window.location = "gameOver.php";
})
To solve this problem you could use cookies.
As mentioned in this stachoverflow thread, you store a cookie the first time someone visits your page. If you check on every page load if the cookie is set, you can detect if somebody has reloaded the page.
If you plan to create a "Play again" function you can simply destroy the cookie.
To get a look of the code look to the linked stackoverflow question above!
use cookie or localstorage first time someone visits the page. On refresh the check if your cookie or localstorage value is exists and if it does then redirect them to gameOver.php using javascript.
function checkUserVisit() {
if(document.cookie.indexOf('visit')==-1) {
document.cookie = 'visit=true';
}
else {
window.location = "gameOver.php";
}
}
call this function on body load of page.
<body onload="checkUserVisit()">
I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation
I want to alert() when browser's back or forward button is clicked or hash is changed in javascript. I have tried this solution and it is working but it is causing problems on other links in webpage and submit each request twice on any link click event.
Is there any solution to capture it without using setInterval() function? So I need to capture hash change or back/forward button click event? I need a simple javascript code/function/property that should work in all modern browsers.
Any solution ?
Thanks
Not a good idea
Can you rather explain the reasoning behind this? We've all been down this road of preventing backs/forwards and similar and mangling with browser functionality.
It turns out though it's better to obey to browser and write your application in that way so these things become irrelevant. And it's also true that browsers are locking more and more things to client javascript apps so it's highly likely your app is going to fail after (few) browser upgrades.
Go with HTML5
HTML5 History spec may be exactly what you're after. It's the way things should work and be done in regard to Ajax applications and browser0s back/forward functionality. I suggest you check it out. See a working demo that does this rather nicely.
I believe this is the answer Robert Koritnik was looking for, I found it here: https://developers.google.com/tv/web/articles/location-hash-navigation
There is an event (window.onhashchange) that fires whenever the location hash has been updated or changed so all you have to do is set up an event handler using JavaScript to listen for this event and execute code based on the hash. This is basically how it is done:
function getLocationHash() {
return window.location.hash.substring(1);
}
window.onhashchange = function(e) {
switch(getLocationHash()) {
case 'state1':
execute code block 1;
break;
case 'state2':
execute code block 2;
break;
default:
code to be executed if different from case 1 and 2;
}
}
I have it working on my site:
http://www.designhandler.com
It is all dynamically changing content. No ajax yet but when I am finished it will be. I still use the window.location.hash to keep track of the site states. If you navigate through the site and then begin to use the back forward buttons to navigate once the site is in the history it will change the states dynamically like if the user was actually clicking through the nav, rather than needing to reload the page afterward.
It's this for hash or for redirection? What are you trying to do? This kind of action is usually highly intrusive.
You may want to try "onbeforeunload" event for this javascript before leaving the page
Edited
Actually, the link you provide is quite accurate.
var hash = location.hash;
setInterval(function()
{
if (location.hash != hash)
{
hashUpdatedEvent(hash);
}
}, 100);
function hashUpdatedEvent(hash)
{
switch(...);
}
Your link duplicate action problem would be corrected if you change
Go for it
function someFuncion()
{
doWhatever();
location.hash = 'somethingwasdone';
}
function hashUpdatedEvent(hash)
{
if(hash == 'somethingwasdone')
{
doWhatever();
}
}
By just (update the hash and let the "event" handle the action) :
Go for it
function someFuncion()
{
location.hash = 'somethingwasdone';
}
function hashUpdatedEvent(hash)
{
if(hash == 'somethingwasdone')
{
doWhatever();
}
}
Javascript provide the event popstate to capture browser's back/forward button click event -
window.addEventListener("popstate", function(e) {
// if a back or forward button is clicked, do whatever, like alert or anything
console.log('href => ', e.path[0].location.href);
// href => https://testdomain.com/demos/material/admin-app/#!/app/dashboard
console.log('hash => ', e.path[0].location.hash);
//hash => #!/app/dashboard
console.log('pathname => ', e.path[0].location.pathname);
//pathname => /demos/material/admin-app/
});
Read more on popstate
I have a scenario to refresh the browser after the page is loaded for first time or one time.
Because the data is not showing properly when the pages is loaded,and when i refresh the browser it is showing.I don't know the reason.
Many Thanks
So you only want the browser to refresh once? Do something like this.
window.onload = function(){
if(!document.location.hash){
window.location = "#loaded";
}
}
or jquery
$(document).ready(function(){
if(document.location.hash){
window.location = "#loaded";
}
});
But in all honesty this is just a temporary solution. As much as you try to cover it up with quick fixes. I guarantee it will come back to haunt you. Well written and structured code will last a lifetime and can always be reused on future projects.
Invariably, you're going to have to use some JavaScript. What you want is for your refresh code to run when the page is completely loaded. You could use the HTML onload event, but there are problems with this (e.g. it will fire before any images are loaded). I would suggest using JQuery's ready() event, if you want to be sure it fires after the entire page is loaded.
Example:
// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
location.reload(true);
});
Making this only fire on the first page load is a bit more tricky. You could add an anchor suffix to the URL to keep track of whether you've refreshed the page yet or not, and then only refresh if it is not present in the URL:
$(document).ready(function(){
if(location.hash != "#")
{
// Set the URL to whatever it was plus "#".
// (The page will NOT automatically reload.)
location = "#";
// Reload the page.
location.reload(true);
}
});
Alternatively, you could use the query string, since this will automatically refresh the page when changed:
$(document).ready(function(){
var marker = 'r'; // 'r' is for "refreshed"
if(location.search != "?"+marker)
{
// Set the URL to whatever it was plus "?r".
// (This will automatically force a page reload.)
location = "?"+marker;
}
});
Caveat: With either of these samples, if your user bookmarks the page after the "#" or "?r" tag has been added to the URL, the page won't refresh when they revisit the page. If you want it to be bulletproof, you might have to use a cookie instead.