Skip to content Skip to sidebar Skip to footer

Refresh Page And Run Function After - 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 lo

Solution 1:

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();
    }
}

functionreloadP() {
    sessionStorage.setItem("reloading", "true");
    document.location.reload();
}

DEMO

Solution 2:

functionmyFunction() {
    document.getElementById("welcome").textContent = "Welcome back!";
}

window.onload = function() {
    var reloading = sessionStorage.getItem("reloading");
    if (reloading) {
        sessionStorage.removeItem("reloading");
        myFunction();
    }
}

functionreloadP() {
    sessionStorage.setItem("reloading", "true");
    document.location.reload();
}

DEMO: https://jsfiddle.net/barmar/5sL3hd74/

Solution 3:

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')
    }
}

Solution 4:

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() once you've executed the function after loading the window.

So, let's say we have:

var 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
  }
};

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.

Post a Comment for "Refresh Page And Run Function After - Javascript"