最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Executes js code after redirect to another url - Stack Overflow

programmeradmin1浏览0评论

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('');
}
</script>
</body>
</html>

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>

Share Improve this question edited Jul 29, 2015 at 8:45 Mohit Kanwar 3,0508 gold badges40 silver badges61 bronze badges asked Jul 29, 2015 at 8:18 astropeakastropeak 1471 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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
发布评论

评论列表(0)

  1. 暂无评论