Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

window.location.href = "some_location"; 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.)

like image 413
Lukas Avatar asked Dec 11 '12 00:12

Lukas


People also ask

Does window location href return a string?

The href property of the Location interface is a stringifier that returns a string containing the whole URL, and allows the href to be updated.

What does Window location href return?

The window.location.href property returns the URL of the current page.

Where do you put window onload?

onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


2 Answers

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.

like image 179
jfriend00 Avatar answered Oct 07 '22 16:10

jfriend00


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

Like so:

window.location.href = "http://www.google.com/"; 

Once the browser goes to google.com, 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.

like image 36
mattgmg1990 Avatar answered Oct 07 '22 18:10

mattgmg1990