location.reload(), Javascript,HTML - javascript

I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?

location.reload() will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.

As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.

Related

JS: How to redirect an user to another page when user refresh the page?

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()">

How do I make the page refresh in Javascript

So I want to make a script like this:
window.location = "http://m.roblox.com/Catalog/VerifyPurchase?assetid=122174821&type=robux&expectedPrice=1"
document.getElementsByClassName('buyButtonClass')[1].click()
but I don't know how to make the page refresh and the code start over without it having to manually be entered again
Thanks
By the way it will be running in Google Chrome Dev. tools Console
I tried
function blah() {
// window.location = "http://m.roblox.com/Catalog/VerifyPurchase?
assetid=122174821&type=robux&expectedPrice=1"
document.getElementsByClassName('buyButtonClass')[1].click()
if (some_condition) {
blah() // rerun the code
}
}
Output was "undefined", the script did nothing.
The script goes to a link, clicks a button (currently it doesn't click for some reason) then restarts the script (not working)
setting window.location = ... will refresh the page, but stuff after that will not trigger, because you just refreshed the page including all the javascript. You can put the code you want to trigger in a $(document).ready(function(){your_code_here}); call and when the page refreshes, it will set up your click event.

Jquery Mobile - Javascript persisting when navigating to another page

Hey guys I have a javascript function that keeps persisting even when navigating to another page (single page templates not multipage) in Jquery Mobile
<script type="text/javascript">
setInterval("window.location.reload();", 5000);
</script>
How do I ensure that this only occurs on the page from which it is called rather than it calling it on every page I link to with ajax based navigation?
I am using Jquery Mobile 1.2
Bind it to the page where you want it to occur. Replace $('.selector') with pageID, e.g. $('#home'). You could also be more specific $('div[data-role="page"]#PageID').
// Trigger interval
$('.selector').bind('pageinit', function () {
setInterval("window.location.reload();", 5000);
});
// Stop interval when navigating away
$('.selector').bind('pagehide', function () {
clearInterval();
});
How do I ensure that this only occurs on the page from which it is
called rather than it calling it on every page I link to with ajax
based navigation?
Don't call it? Currently your code is set up to always run when it's included on the page. Either don't include it or prevent it from running in some other way (such as an if-statement).
You could clear the interval just before you navigate.
First you need to get a reference to the interval when you create it:
var intervalRef = setInterval("window.location.reload();", 5000);
Then you can clear it like this:
clearInterval(intervalRef);
// Navigate
Just cancel your timeout when the other page loads, or when the current page exits (the other page loads in ajax so the timed interval stays up).
// trigger
myInterval = setInterval("window.location.reload();", 5000);
// stop
clearInterval(myInterval);

Javascript - Reload page after form submit with target="_blank"

I'm trying to achive the following:
On page A we have an access restricted Link to page B. The access restriction is handled on the server side in PHP.
When a user clicks on this link to page B we display a modal dialogue on page A (via javascript) with a form, having the link's href (B) as the action. (To give the user an immediate feedback. The fallback is to redirect him to a login form that redirects him to the site he wants to access.)
This system works quite well.
But now comes my question:
We have access restricted links that should be opened in a new window.
Now if I use target="_blank" on the form the user stays logged out on the page he came from (A), that is still open in the background.
Is there a way to reload the page (A, in the background) right after the form has been submitted to the new window (B)?
My first idea was to use window.location.reload(); in the submit handler on page A.
This didn't work in chrome and from what I understand could create a race condition.
Another idea would be to log the user in via an ajax call and open a new window through javascript. Is there a way to do this without having to deal with pop-up blockers?
I implemented the idea of lostsource (see below) with one slight addition.
As I need to reload only once, the timer of setInterval can be stopped if the cookie changed.
var ri=setInterval(function() {
if(oldCookie != document.cookie) {
// assuming a login happened, reload page
clearInterval(ri);
window.location.reload();
}
},1000); // check every second
I still love the idea. stackoverflow is awsome!
Assuming you're storing PHP session information inside a cookie, you might be able to monitor your document.cookie for changes.
Before submitting the form store the value of the current cookie and monitor it for changes with a timer:
form.onsubmit = function() {
var oldCookie = document.cookie;
var cookiePoll = setInterval(function() {
if(oldCookie != document.cookie) {
// stop polling
clearInterval(cookiePoll);
// assuming a login happened, reload page
window.location.reload();
}
},1000); // check every second
}
On the parent page, do you have any visual/functional changes because of the login? As in any new actions possible?
If not, then you dont have to do anything as you would be checking for login on every action from the parent page, you can check for permissions along with that.
If there are changes or additional functionalities, you can call a javascript function in the parent, say reloadMe, using window.opener.reloadMe()
Why not just a simple setTimeout
setTimeout(function(){ location.reload(); }, 1000);
It is a bit hacky, but seems appropriate for your situation.

How to check page is reloading or refreshing using jquery or javascript?

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

Categories