Is there a way to have an onload callback after changing window.location.href?

Essentially what I’d like to do is something to the effect of this:

window.location.href = "";
window.onload = function() {
  alert("I'm the new location and I'm loaded!");

Is there any way to have a callback when the window’s new location is loaded? (The above code doesn’t work.)

No, you cannot do it the way you want. Loading a new page closes the current document and starts loading a new document. Any code in your current document will no longer be active when the new page starts to load.

To have an event handler when the new document loads, you would either need to insert code into the new page’s document or load the new document into an iframe and monitor the loading of the iframe from your current document.

Setting window.location.href to a new value tells the browser to simply go to the next page.

Like so:

window.location.href = "";

Once the browser goes to, that’s it, your Javascript is no longer executing, and there is no way for you to have any sort of callback, because the browser is no longer running your page.

So, the answer is no.

in regards to callback and js execution in new context – no (as per orig answer), but there are ways to access loaded elements without callback. For e.g. scrollIntoView on a loaded element, you can append the selector:

const href="#someElem"
if(window.location.pathname  !== "") window.location.href = `/${href}`
else document.querySelector(href).scrollIntoView() 

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Where to put model data and behaviour? [tl; dr; Use Services]

Similar Posts