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


Solution 1:[1]

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/

Solution 2:[2]

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 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Félix Pujols
Solution 2 MrAlbino
Solution 3