I have the code below which asks for confirmation when a user tries to reload the page. It works fine
window.onbeforeunload = function(event) {
return confirm('Confirm refresh');
};
In another part of the code, I am redirecting it to the page using window.location.href It returns a popup whether you want to leave the page. How can I avoid this popup when using window.location.href?
window.location.href = window.location.href.split('#')[0];
You could just set a variable to skip this behaviour :
let skipUnloadConfirm = false;
window.onbeforeunload = function(event) {
if(!skipUnloadConfirm) {
return confirm('Confirm refresh');
}
};
And then change value before setting href (function would replace direct window.location.href assignement and could be reused)
function redirect(url) {
skipUnloadConfirm = true;
window.location.href = url;
}
Or, you can override window.onbeforeunload before calling redirect
I have an window.onload function that does not run when a user manually refreshes the page. I have noticed that on the page refresh, the URL is appended with a # at the end, but I don't know if that has anything to do with the error. The function correctly executes when first loaded, but not after a refresh.
window.onload = function() {
alert("HERE");
var a = document.getElementById("link1");
a.onclick = function() {
var current = window.location.href;
alert(current);
if (current.indexOf("&page=") != -1) {
current = current.substring(0,current.indexOf("&page="));
}
var nextPage = current + "&page=link1"
window.location.replace(nextPage);
return false;
}
}
UPDATE: It seems as though it is working in Chrome, but not Safari.
Also, additional information, my a tag looks like this:
<a id='link1' href='#'>Link 1</a>
try using :
$(document).ready(function() {
});
instead.
check if it helps..
I have a sample page, let' say testpage.pl When I choose English version, GET parameter is added to URL, like /?language=en.
Afterwards, when I click menu positions, they are in the English version so everything is OK.
But if I want to have English version of a subpage directlty after pasting URL in a browser, like
http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html)
the Polish version is opened. So I've made a simple redirect function like below, but it comes to the loop after first start. This function redirect to the same page, but before it tries to redirect to this first URL with GET parameter ?language=en
How to solve this?
function cleanUrl() {
window.location = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();
Your are updating url in first line of function which is causing your code to loop infinite. Remove that line or move to some other function for fix
function cleanUrl() {
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = "http://testpage.pl/?language=en";
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();
Keep the window.location assignment as last operation.
function cleanUrl() {
var enUrl = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if( currentUrl !== cleanedUrl ) { enUrl = cleanedUrl; }
window.location = enUrl;
}
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.
I would like to implement a JavaScript code which states this:
if the page is loaded completely, refresh the page immediately, but only once.
I'm stuck at the "only once":
window.onload = function () {window.location.reload()}
this gives a loop without the "only once". jQuery is loaded if this helps.
I'd say use hash, like this:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
When I meet this problem, I search to here but most of answers are trying to modify existing url. Here is another answer which works for me using localStorage.
<script type='text/javascript'>
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
</script>
<script type="text/javascript">
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution.
This works for me fine.
Check this Link it contains a java-script code that you can use to refresh your page only once
http://www.hotscripts.com/forums/javascript/4460-how-do-i-have-page-automatically-refesh-only-once.html
There are more than one way to refresh your page:
solution1:
To refresh a page once each time it opens use:
<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
sollution2:
<script language=" JavaScript" >
<!--
function LoadOnce()
{
window.location.reload();
}
//-->
</script>
Then change your to say
<Body onLoad=" LoadOnce()" >
solution3:
response.setIntHeader("Refresh", 1);
But this solution will refresh the page more than one time depend on the time you specifying
I hope that will help you
<script>
function reloadIt() {
if (window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
}
setTimeout('reloadIt()', 1000)();
</script>
this works perfectly
Finally, I got a solution for reloading page once after two months research.
It works fine on my clientside JS project.
I wrote a function that below reloading page only once.
1) First getting browser domloading time
2) Get current timestamp
3) Browser domloading time + 10 seconds
4) If Browser domloading time + 10 seconds bigger than current now timestamp then page is able to be refreshed via "reloadPage();"
But if it's not bigger than 10 seconds that means page is just reloaded thus It will not be reloaded repeatedly.
5) Therefore if you call "reloadPage();" function in somewhere in your js file page will only be reloaded once.
Hope that helps somebody
// Reload Page Function //
function reloadPage() {
var currentDocumentTimestamp = new Date(performance.timing.domLoading).getTime();
// Current Time //
var now = Date.now();
// Total Process Lenght as Minutes //
var tenSec = 10 * 1000;
// End Time of Process //
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
location.reload();
}
}
// You can call it in somewhere //
reloadPage();
i put this inside my head tags of the page i want a single reload on:
<?php if(!isset($_GET['mc'])) {
echo '<meta http-equiv="refresh" content= "0;URL=?mc=mobile" />';
} ?>
the value "mc" can be set to whatever you want, but both must match in the 2 lines. and the "=mobile" can be "=anythingyouwant" it just needs a value to stop the refresh.
Use window.localStorage... like this:
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
It works for me.
After </body> tag:
<script type="text/javascript">
if (location.href.indexOf('reload')==-1)
{
location.href=location.href+'?reload';
}
</script>
You can make one verable once = false then reload your page with if else like if once == false reload page an make once true.
You'd need to use either GET or POST information. GET would be simplest. Your JS would check the URL, if a certain param wasn't found, it wouldn't just refresh the page, but rather send the user to a "different" url, which would be the same URL but with the GET parameter in it.
For example:
http://example.com -->will refresh
http://example.com?refresh=no -->won't refresh
If you don't want the messy URL, then I'd include some PHP right at the beginning of the body that echos a hidden value that essentitally says whether the necessary POST param for not refreshing the page was included in the initial page request. Right after that, you'd include some JS to check that value and refresh the page WITH that POST information if necessary.
Try with this
var element = document.getElementById('position');
element.scrollIntoView(true);`
Please try with the code below
var windowWidth = $(window).width();
$(window).resize(function() {
if(windowWidth != $(window).width()){
location.reload();
return;
}
});
Here is another solution with setTimeout, not perfect, but it works:
It requires a parameter in the current url, so just image the current url looks like this:
www.google.com?time=1
The following code make the page reload just once:
// Reload Page Function //
// get the time parameter //
let parameter = new URLSearchParams(window.location.search);
let time = parameter.get("time");
console.log(time)//1
let timeId;
if (time == 1) {
// reload the page after 0 ms //
timeId = setTimeout(() => {
window.location.reload();//
}, 0);
// change the time parameter to 0 //
let currentUrl = new URL(window.location.href);
let param = new URLSearchParams(currentUrl.search);
param.set("time", 0);
// replace the time parameter in url to 0; now it is 0 not 1 //
window.history.replaceState({}, "", `${currentUrl.pathname}?${param}`);
// cancel the setTimeout function after 0 ms //
let currentTime = Date.now();
if (Date.now() - currentTime > 0) {
clearTimeout(timeId);
}
}
The accepted answer uses the least amount of code and is easy to understand. I just provided another solution to this.
Hope this helps others.
React Hook worked for me.
import { useEffect, useState } from 'react';
const [load, setLoad] = useState(false);
window.onload = function pageLoad() {
if (load) {
window.location.reload(true);
setLoad(false);
}
};
nothing work for me perfectly except this, -added to my JavaScript file-:
function LoadOnce() {
if (localStorage.getItem('executed') == 'false') {
window.location.reload()
localStorage.setItem('executed', true)
}
}
setTimeout(function () {
LoadOnce()
}, 100)
and in the previous page I wrote:
localStorage.setItem('executed', false)
I got the Answer from here and modified it.This is the perfect solution for me.
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
setTimeout(function() {
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
}, 1500); // 1500 milliseconds = 1.5 seconds
setTimeout(function() {
localStorage.removeItem('refresh')
}, 1700); // 1700 milliseconds = 1.7 seconds
var foo = true;
if (foo){
window.location.reload(true);
foo = false;
}
use this
<body onload = "if (location.search.length < 1){window.location.reload()}">
Use rel="external"
like below is the example
<li>Home</li>