You simply can't do what you're trying to do. When the page is changed to "http://example.com"
, this sets in motion a series of events which will eventually result in your entire Javascript context being stopped. You can't run Javascript from this page in the new page.
When you assign:
window.location = "http://example.com";
This begins a process which will stop the execution of the Javascript in the current page. The current page is unloaded and all memory associated with it is freed. Then, a new page is loaded, a new Javascript context is created and the Javascript in that new page is then loaded and run.
The usual way to communicate with a new page is to put the Javascript that wants to run in that new page and then send some parameters to that new page that its Javascript can detect and react accordingly.
For example, you might do this:
window.location = "http://example.com?doSomething=whatever";
And, then when the new page is loaded, the Javascript in THAT page can check the query string to see if any special arguments were passed to it. If they were, then that Javascript can parse them and decide what behavior to carry out based on those query string parameters.
Another possibility is to not use window.location
. You can, instead, fetch new HTML via Ajax and then use Javascript in the current page to insert that new content into the current page (or replace existing content with new content). With jQuery, you can use jQuery's .load()
to load content from a URL directly into an element in the current page like this:
$("#myDiv").load(someURL);
Since this is Ajax, it has all the normal cross-origin restrictions that any Ajax call might have so you can't freely load pages from other websites (unless they permit cross origin access).