在由Javascript打开的窗口上附加onload处理程序 [英] Attach an onload handler on a window opened by Javascript

查看:76
本文介绍了在由Javascript打开的窗口上附加onload处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够知道用户何时离开我在Javascript打开的窗口中加载的页面。例如,如果我有:

I want to be able to know when a user navigates away from the page I have loaded in a window opened by Javascript. For example if I have:

newWindow = window.open('http://www.example.com', 'testWindow');

我想知道用户何时离开该页面(因此卸载,onunload,onbeforeunload将全部如果可以的话,为我工作)。新窗口来自不同的域名,所以也许有一些相同的原始政策正在进行,但我已经能够使用iframe。例如:

I want to know when the user navigates away from that page (so unload, onunload, onbeforeunload would all work for me if any could be attached). The new window is from a different domain so maybe there's some same origin policy going on but I've been able to do it with iframes. For example:

<iframe src='http://www.example.com' onload='alert("load");'><iframe>

工作正常,但我需要为窗口而不是iframe执行此操作。

works just fine but I need to do this for a window, not an iframe.

推荐答案

你可以这样做:

newWindow = window.open('http://www.example.com', 'testWindow');
newWindow.onload = function() {
  alert("loaded");
};

你可以在这里尝试一下。但是有一些限制,窗口必须位于同一个域,以符合同源策略 onload 事件不会被连接起来)。在示例中,奇怪的域与测试帧相同,这非常重要...尝试更改域或协议,您将看到它不起作用,并且您将在控制台中收到错误。

You can give it a try here. There are restrictions however, the window must be on the same domain, to be in compliance with the same-origin policy (the onload event just won't be hooked up otherwise). In the example that weird domain is the same as the test frame, this is very important...try changing the domain or protocol and you'll see it doesn't work, and you'll get an error in your console.

这篇关于在由Javascript打开的窗口上附加onload处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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