Can I run javascript Code after reloading the page?
In my case I want to enter the code in the address bar via javascript: <<CODE>>
to reload a page several times and check if a button with a special id exists and to click it. Here is my Code:
function check () {
if(new Date().getTime >= 1442949420000) {
var loginbtn = document.getElementById('loginbutton');
if(loginbtn){
loginbtn.click();
} else {
console.log('button not yet here - reload');
window.location.reload();
check();
};
} else {
console.log('to early - reload');
window.location.reload();
check();
};
};
check();
The problem is, that the page reloads after window.location.reload()
and the check()
function never gets called, so the page just reloads once.
Or is there a service, that injects my script to a url?
You need to call myFunction() when the page is loaded. window. onload = myFunction; If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.
You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.
In JavaScript, you refresh the page using document. location. reload() . You can add the true keyword to force the reloaded page to come from the server (instead of cache).
Finally, if you call the “reloadPage();” function in your Javascript file, it will only reload the page once.
You can add a URL fragment to the address bar, and then reload the page. So, before the reload, your would be at http://yoursite.com/yourPage
and after the reload, you could be at http://yoursite.com/yourPage#reload
. Here is a simple working example for something along those lines:
document.getElementById("clickMe").onclick = function clicked(){
window.location.hash = 'reload';
window.location.reload();
}
//When the document has loaded, call the function
document.addEventListener("DOMContentLoaded", function(event) {
if(window.location.hash == "#reload"){
console.log("The Page has been reloaded!");
}else{
console.log("The page has a new hit!");
}
});
<button id="clickMe" type='button'>click</button>
When you click the button, the hash is added to the window location, and then the page is reloaded, with the URL fragment attached. I then decide in the document ready function if the page has been reloaded or not. Make sure to test it locally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With