How to refresh page on back button click? - javascript

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.

Related

Prevent from running a js file in all the indexed pages

I'm coding a website with multiple pages (indexed to the index.html) with different content but one header and one footer. The problem is that I linked my footer.js file to all the pages (considering that it needs the same code) but the issue is that it's loading simultaneously when loading multiple pages.
It's a jquery pop-up so when I click to display it in index.html, it's also displayed in contact.html
I don't want to modify my code for every single page, specially because it will be dynamic after.
So here's my javascript :
//open popup
$('.cdv').on('click', function(event){
event.preventDefault();
$('.cd-popup').addClass('is-visible');
});
//close popup
$('.cd-popup').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('.cd-popup') ) {
event.preventDefault();
$(this).removeClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
$(document).keyup(function(event){
if(event.which=='27'){
$('.cd-popup').removeClass('is-visible');
}
});
//open popup
$('.pdq').on('click', function(event){
event.preventDefault();
$('#cd-popup-politique').addClass('is-visible');
});
//close popup
$('#cd-popup-politique').on('click', function(event){
if( $(event.target).is('.cd-popup-close') || $(event.target).is('#cd-popup-politique') ) {
event.preventDefault();
$(this).removeClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
$(document).keyup(function(event){
if(event.which=='27'){
$('#cd-popup-politique').removeClass('is-visible');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do it in two ways, the first is checking the url pathname and executing code to show a popup only if it meets your criteria
var location = window.location.pathname;
// assume it's an index page
if (location === '/') {
// execute your code to show a popup
}
If your pathname will contain GET attributes, use .indexOf() instead
For this solution you will need to compare pathname to either / or index.html, depending on your server set-up.
Second solution might be a global variable in .html file, for example just before you include your main javascript file.
<script>
window.popup = true;
</script>
And then you can check inside your javascript if this variable has a true value and execute your code.
if (window.popup === true) {
// show popup
}
Documentation: Window.location - mdn
Thank you guys for the help but I think that I solved the problem.
Actually what's causing this bug is Codekit (I use it to compile my SASS files and to minify js files). I can't explain why but when I tried it locally without the software and pushed it to github to see if it works, than it worked.
So if someone can explain it will be great, otherwise for all those who are facing the same problem, just don't care about codekit if you're running it.
Thank you.

Javascript : make request again when accessing previous state

I use this in my JS:
window.history.replaceState({url: , scrollTop: wTop}, 'foo', 'bar');
But when I go to another page from here then press the back button, I end up not firing a request. Instead, my browser loads everything back from its "disk cache". I'd like to fire the request again, since my state has change and it should ask for the corrected page.
How can I achieve that?
I tried with this in my rails controller:
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
But apparently, the history list is not entirely related to the cache feature.
I'd do it with a hidden input and a bit of script. Something like the following assuming you have jQuery available (obviously just modify it if you're not using it):
<input type="hidden" id="reload_page" value="false" />
And then:
$(document).ready(function() {
if ($("#reload_page").val() == "true") {
location.reload(true);
} else {
$("#reload_page").val("true");
}
}
The "true" flag in the location.reload event tells it to reload the page from the server instead of from the cache. The browser should store your input value as part of the cache, so the page will refresh when you return to it, but not when it first loads.
If you're working with a page that has been added instead, so that it has no historical state, you can reverse the process a little -- instead of a direct reload, as in the above, add a form to submit rather than a direct reload, something like the following:
<form id="reload_form" method="get">
<input type="hidden" id="no_refresh" val="true" />
</form>
Paired with a similar bit of script:
$(document).ready(function() {
if (!$.urlParam('no_refresh')) {
$("#reload_form").submit();
}
});
This makes use of the $.urlParam function found here, but works on a similar principle to the natural "back" function in the snippet above -- once the form is submitted to refresh the page, the parameter becomes available, and the changed state prevents the script from refreshing the page.
You need to add a pop state listener.
window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
If you don't add this listener, then the browser will behave in the traditional fashion, requesting the page from the server (or loading from cache) when the state changes.
NOTE: The browser caching header can still be used with push/pop state which improves first page loading.

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

Direct to another page if refresh button is pressed

When the refresh button is pressed, I would like to send the user to a different page using PHP or javascript.
That is,
if (refresh pressed) header('Location: Some_Page.php');
Can anyone tell me how is it possible?
Although you tagged your question as javascript, you did also tag it as php
You could use sessions for this. Here is what I tried that worked.
I set the conditional statement to 10 (for testing purposes), but you can make it as 1 or any other number you wish.
N.B.: ob_start(); is required, otherwise it will throw an headers already sent error message.
<?php
ob_start();
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
if ($_SESSION['views']== 10){
header("Location: http://www.example.com/");
}
?>
Footnotes: If you use this, session_start(); (and maybe ob_start(); if using header()) needs to be inside all files using the same session, and at the top as shown.
So, I don't think you can hook into a specific page refresh event (I don't think it exists), you can hook into a page unload via javascript, which would be fired on a page refresh event. You would use the onunload or onbeforeunload event to trigger saving the state in cache or a cookie. (you could also on timeouts set the state every x seconds during normal gameplay)
You cannot alert or redirect with hooking into the unload or onbeforeunload events.
the following was my original suggestion, before I tested and found you cannot do the page navigation from the onunload and onbeforeunload events
You would also want to set a boolean saying game place has started, check for the boolean in the unload event (set that boolean to false after game is complete). That way you do not do a redirect when the user wants to actually navigate away from your game.
window.onbeforeunload=function(){window.location.replace(...)};
window.location.href=... would also work in the context of the onunload event.
Event click on Refresh button equals event of exiting current page. Use next:
// jQuery
$('body').bind('beforeunload',function(e){
e.preventDefault();
var url = "http://stackoverflow.com";
$(location).attr('href',url);
});
// JS
window.onbeforeunload = function (e) {
e.preventDefault();
var url = "http://stackoverflow.com";
// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else window.location.replace(url);
};

How to reload a page only once everytime it gets loaded

I have a JSP page that is showing previous content even after deleting one of the content. I am working to find the problem but I need a quick fix for this. I'm weak in JavaScript so please help me out. I need a JavaScript that would reload the page automatically every time the page is visited. Reloading the page does solve the problem.
If you want to do it just once, I would use localStorage:
if (localStorage.getItem('loadedOnce') === 'true') {
// don't reload page, but clear localStorage value so it'll get reloaded next time
localStorage.removeItem('loadedOnce');
} else {
// set the flag and reload the page
localStorage.setItem('loadedOnce', 'true');
document.location.reload(true);
}
I would really recommend looking into why this is broken, instead of trying to hack around the problem.
Note:
This doesn't work in older browsers. See mdn's compatability table for more information (IE8 does support it however).
Based on #Omar's answer, and similar to tjameson's. It just uses cookies instead.
var int=self.setTimeout(function(){refresh()},1000);
function refresh() {
if (document.cookie.indexOf("reloaded") === -1){
document.cookie += ";reloaded";
document.location.reload(true);
}
else {
document.cookie = document.cookie.replace(/;reloaded/g, '');
}
}

Categories

Resources