简体   繁体   中英

Executes js code after redirect to another url

I have a page as below, when user clicks the Go href, it will redirect to another page. I want to do some JS manipulations on the redirected page after the page is fully loaded, but have trouble in doing this.

I tried to achieve this by putting all JS manipulations statements to a setTimeout function, but it seems the statements will not be executed after the redirected page is loaded. In below example, alert('in settimeout') was not executed.

Can you tell me how to achieve this? Thanks!

 <!DOCTYPE html> <html> <body> <a href="#" onclick="foo()">Go</a> <script> function foo(){ setTimeout(function (){ alert('in settimeout'); // **this will not be executed.** //js manipulations here ... }, 5000); window.location.replace('http://onlineapp.ws'); } </script> </body> </html> 

You can't run JavaScript after you've destroyed the environment it runs in. Leaving a page will destroy that environment.

The only ways to do this would be to:

  • load the new page in a frame (and the new page would have to be on the same origin ) and then access it using the frames API .
  • pass some information to the server hosting the new page (eg via the query string) and read that to determine if the JS should run or not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM