Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (e.g. via the query string) and read that to determine if the JS should run or not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...