execute js function after reloading page [duplicate] - javascript

I'm trying to refresh a page and then run a function once the refresh has been completed. However the code I have now, runs the function and then it only refreshes it, meaning I lose what the function did. Is there a way to solve this?
My code
function reloadP(){
document.location.reload();
myFunction();
}
<button onclick: "reloadP()">Click</button>

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.
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO

function myFunction() {
document.getElementById("welcome").textContent = "Welcome back!";
}
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO: https://jsfiddle.net/barmar/5sL3hd74/

Adding to #Barmar answer... In case you'd like to use session storage only when a button in the page is clicked and not when reloading with the browser button, you can use sessionStorage.clear() or sessionStorage.removeItem() once you've executed the function after loading the window.
So, let's say we have:
let restart = sessionStorage.getItem("restart")
Set restart boolean to true as a session storage and reload:
resetBtn.addEventListener("click", () => {
sessionStorage.setItem("restart", "true")
location.reload()
})
Once the window is reloaded we can execute the following function:
window.onload = () => {
if(restart){
// Do something
sessionStorage.clear() // This cleans all the session storage
// If you want to remove ONLY the item from the storage use:
// sessionStorage.removeItem("restart")
}
};
So, if now the user reloads the page with the browser button it will reload with the session storage cleaned. Meaning, no functions will be executed after window load.

In my case i used Barmar's solution. I have a modal popup form, i want to submit the form then automatically refresh the page and finally success message on reloaded page.
var form = document.getElementById('EditUserInfosForm')
form.addEventListener('submit', function () {
sessionStorage.setItem("reloading", "true");
document.location.reload();
})
window.onload = function () {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
$('#success-message-modal').modal('show')
}
}

Probably simplest approach.
HTML Button
Reload button (credits):
<!-- index.html -->
<button onClick="window.location.reload();">Refresh Page</button>
JS Code
Run your code after reload:
// index.js
window.addEventListener("load", (event) => {
YourFunction(); // already declared somewhere else
});
You may not use event variable at all.
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#examples

Related

How can i handle page refresh event in React.js

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave.
but issue is that when user refresh page using browser refresh btn in google chrome that time below error occur
I tired this code but doesn't work in react.js please help
window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
if (!window.hideWarning) {
event.preventDefault();
event.returnValue = '';
}
});
Also try this code
window.onbeforeunload = function () { return ''; }.bind(this);
Try this code it's work for me
window.onbeforeunload = function () {
if ("Some condition") {
return '';
}
}.bind(this);
you can also use that
winodow.location.reload(true)
winodow.location.reload(false)
Please use this:
console.log(window.performance.navigation)

Can we have code after location.reload(true)?

I have a function that does a reload from server with:
location.reload(true)
Currently, any code I have after this line is not executed.
I'm curious if there is a way to be able to have more code run after the reload?
The best way to do this would be to write a function that is called if there are certain "GET" variables set and to check them on each run such as mypage.html?reload=true
Or even hash locations: mypage.html#reload
And you can compare like so:
$(document).ready(function () {
if (window.location.hash == '#reload') {
onReload();
}
});
function onReload () {
console.log('test');
}
function reload () {
window.location.hash = 'reload';
window.location.reload();
}
Just call the reload(); function.
Output (in console): test
And then you can just redirect people away from the hash #reload if you don't want your function to run if the page is refreshed again: window.location.hash = '';
why you need execute something after reload the page?
If you need to do something after reload, so you can pass some parameter to the page and check this to execute something additional. You can redirect to the same page and pass a complete url
var url = window.location.href;
url += '&param=1'
window.location.href = url;
So, when your page reload, you can check a parameter by GET and do whatever you want. I hope this trick help you!
________________METHOD 1: WITH PHP_________________
1) reloading with a parameter
2) getting that parameter with PHP
For example:
window.location.href += '&reloading=1';
//it's equivalent to:
//window.location.href = window.location.href + '&reloading=1';
And then:
<?php
if (isset($_GET['reloading'])) {
echo '<script>pageReloaded();</script>';
}
?>
Since PHP will be executed first, that little script (the function call) will be writen and then executed in javascript, so pageReloaded() function will be called.
A full example would be:
<?php if (isset($_GET['reloading'])) echo '<script>pageReloaded();</script>'; ?>
<script>
function reloadNow(){
alert("I'm about to reload");
window.location.href += '&reloading=1';
}
function pageReloaded(){
alert("I've been reloaded!");
}
</script>
<button onclick="reloadNow()">Press to reload</button>
________________METHOD 2: NO PHP, ONLY JAVASCRIPT_________________
Using SessionStorage
1) Set SessionStorage.
2) Reload
3) Get that SessionStorage
For example:
<script>
function reloadNow(){
alert("I'm about to reload");
sessionStorage.setItem('reloading',"true");
window.location.reload(true);
}
//when loading:
if (sessionStorage.getItem('reloading') === "true") {
sessionStorage.clear(); //so it doesn't trigger next time
alert("I've been reloaded!");
}
</script>
<button onclick="reloadNow()">Press to reload</button>

run function only once on first pageload

i have 3 divs , i want that on first time the page is loaded the function init runs,not again after tht on refresh or reload of page. but its not working below is my code, it runs the code even on refresh or reload of the page.
function _(x){
return document.getElementById(x);
}
$(document).ready(function(){
init();
});
function init() {
_("page1_id").style.display = "none";
_("page2_id").style.display = "none";
_("page0_id").style.display = "block";
}
i am a newbie so kindly share the code tht i need to add or change..thank u
Set a cookie init_run = true
then check it before running init()
or inside the init function:
function init (){
if ( cookie is set )
return;
...
}

jQuery .load: any way to load the same page when page is refreshed

So I have a website that loads pages to a container div:
function goto(addr) {
$("#content").load(addr);
}
and a link that executes it
About us
My problem is that whenever the page is refreshed, the loaded content resets to the default page (page/home.php). How could I do so that it loads the previous displayed page?
Use local storage for example or sessions.
Local storage example:
$(document).ready(function() {
var lastPage = localStorage['lastPage'];
if (!lastPage) { // If user was on any url before we will exectue goto function
goto(lastPage)
}
function goto(addr) {
localStorage['lastPage'] = addr; // Set url to local storage before load page
$("#content").load(addr);
}
});
not only localStore but you need change the hash of url, and after do one function to catch hash code and execute at you "goto" function...
"something like that"
function hashnav(){
var hashfull = document.location.hash
var hash = hashfull.replace('#', '');
var $page = '';
goto(hash);
}
function changeHash($hash) {
window.location.hash = $hash;
}
function goto(addr) {
changeHash(addr);
}
$(window).bind( 'hashchange', function() {
hashnav();
return false;
});

onbeforeunload function having serious issue

I am using native.history.js to put a customised URL in the back button.
The script works fine. Now the issue is I want to make a page redirect when the refresh button is clicked; so i modified the script like this:
<script>
var back = 0;
$(window).bind('beforeunload', function () {
if (confirm('Want to continue?')) {
if (back == 1) {
alert('back');
//window.location.href = "<?=$$last_offer?>";
} else {
alert('refresh');
//window.location.href = "<?=$actual_link;?>";
}
} else {
// Do nothing!
}
});
window.onpageshow = function (e) {
if (e.persisted) {
location.reload();
}
};
window.onpopstate = function (event) {
if (document.location.toString().indexOf("redir=1") > 0) {
back = 1;
window.location.href = "<?=$$last_offer?>";
}
};
</script>
Issue is, the beforeunload function seems not working.
What is the problem I can't fin?.
If I am clicking the back button, the page is taking to the desired page, so it works fine.
All I want is that, somehow the page refresh must work as I anticipated.
Try use
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
Instead of bind, use on, i dont know what jquery version you use, but i will suggest "on".
Works fine here:
link
on jquery version 2.x(edge)

Categories

Resources