重定向到其他网址后执行js代码 [英] Executes js code after redirect to another url

查看:106
本文介绍了重定向到其他网址后执行js代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面如下,当用户点击Go href时,它会重定向到另一个页面。在页面完全加载后,我想在重定向的页面上执行一些JS操作,但在执行此操作时遇到麻烦。

我试图通过将所有JS操作语句放入setTimeout函数来实现此目的,但似乎在加载重定向页面后语句不会执行。在下面的例子中,alert('in settimeout')没有执行。



你能告诉我如何实现这个吗?谢谢!

<!DOCTYPE html>< html>< body>< a href =#onclick =foo( )> Go< / a>< script> function foo(){setTimeout(function(){alert('in settimeout'); // **这不会被执行。 ...},5000); window.location.replace( 'http://onlineapp.ws');}< /脚本>< /体>< / HTML>

当你销毁运行的环境后,你不能运行JavaScript。将破坏该环境。



唯一的方法就是:


  • 在框架中加载新页面(新页面必须位于同一来源),然后使用框架API
  • 将一些信息传递给托管新页面的服务器(例如通过查询字符串)并读取该信息以确定JS是否应运行或不是

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

这篇关于重定向到其他网址后执行js代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆