开发者

Attach an onload handler on a window opened by 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.exa开发者_如何学编程mple.com', 'testWindow');

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>

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


You can do it like this:

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜