Javascript 检测使用 window.open 打开的窗口的 onload 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3030859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:59:41  来源:igfitidea点击:

Detecting the onload event of a window opened with window.open

javascriptinternet-explorerfirefoxgoogle-chromepopup

提问by Christopher Tarquini

 window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
 $(window.popup).onload = function()
        {
                alert("Popup has loaded a page");
        };

This doesn't work in any browser I've tried it with (IE, Firefox, Chrome). How can I detect when a page is loaded in the window (like an iframe onload)?

这在我尝试过的任何浏览器(IE、Firefox、Chrome)中都不起作用。如何检测页面何时加载到窗口中(如 iframe onload)?

采纳答案by Tim Down

If the pop-up's document is from a different domain, this is simply not possible.

如果弹出窗口的文档来自不同的域,这是不可能的。

Update April 2015: I was wrong about this: if you own both domains, you can use window.postMessageand the messageeventin pretty much all browsersthat are relevant today.

2015 年 4 月更新:我错了:如果您拥有这两个域,window.postMessagemessage几乎可以在当今相关的所有浏览器使用事件

If not, there's still no way you'll be able to make this work cross-browser without some help from the document being loaded into the pop-up. You need to be able to detect a change in the pop-up that occurs once it has loaded, which could be a variable that JavaScript in the pop-up page sets when it handles its own loadevent, or if you have some control of it you could add a call to a function in the opener.

如果没有,如果没有将文档加载到弹出窗口中的帮助,您仍然无法使这项工作跨浏览器工作。您需要能够检测弹出窗口加载后发生的更改,这可能是弹出页面中的 JavaScript 在处理自己的load事件时设置的变量,或者您是否可以对其进行一些控制您可以在 opener 中添加对函数的调用。

回答by Delan Azabani

var myPopup = window.open(...);
myPopup.addEventListener('load', myFunction, false);

If you care about IE, use the following as the second line instead:

如果您关心 IE,请改用以下内容作为第二行:

myPopup[myPopup.addEventListener ? 'addEventListener' : 'attachEvent'](
  (myPopup.attachEvent ? 'on' : '') + 'load', myFunction, false
);

As you can see, supporting IE is quite cumbersome and should be avoided if possible. I mean, if you need to support IE because of your audience, by all means, do so.

正如你所看到的,支持IE是相当繁琐的,应该避免可能的话。我的意思是,如果你因为你的观众而需要支持 IE,一定要这样做。

回答by ekim

As noted this answer's https://stackoverflow.com/a/3030893aka Detecting the onload event of a window opened with window.opensolution is ideal:

如上所述,这个答案的https://stackoverflow.com/a/3030893aka检测使用 window.open解决方案打开的窗口的 onload 事件是理想的:

javascript: /* IE will use 1 ignore 1 w/ error, FF t'other way 'round */
 (function(ow){
   ow . addEventListener(  'load', function(){alert("loaded")}, false);
   ow .      attachEvent('onload', function(){alert("loaded")}, false);
  }(window.open(prompt("Where are you going today?",location.href),"snapDown")))

However, other comments and answers perpetrate several erroneous misconceptions as explained below.

然而,如下所述,其他评论和答案犯下了几个错误的误解。

The following script demonstrates the temperamental temporal fickleness of defining onload. Apply the script to a fast loading location.hrefsuch as file:///and some slow site to see the problem. It is possible to see either onloadmessage or none at all (by reloading a loaded page all 3 variations can be seen). It is also assumed that the page being loaded itself does not define an onloadevent which would compound the problem.

以下脚本演示了定义onload. 将脚本应用于快速加载(location.href例如file:///某些慢速站点)以查看问题。可以看到onload消息或根本不看到消息(通过重新加载加载的页面,可以看到所有 3 个变体)。还假设正在加载的页面本身没有定义一个onload会使问题复杂化的事件。

The onload's event handler definitions are definitely not "inside popup's HTML markup" though they will ultimately reside in the DOM of the body... of the HTML.

onload的事件处理程序定义绝对不是‘里面弹出的HTML标记’,虽然他们最终将驻留在的DOM中body...的HTML

javascript:
window.popup=window.open(location.href,'snapDown');
window.popup.onload=function(){alert("message one ")};
alert("message 1 maybe too soon\n"+window.popup.onload);
window.popup.onload=function(){alert("message two")};
alert("message 2 maybe too late\n"+window.popup.onload);

what you can do:

你可以做什么:

  • open a foreign URL
  • on that foreign URL pg. address bar enter a javascript: ...URI
    it will inherit the same-site policies as the foreign URL
    NB. the javascript may need to be bookmarked as a bookmarklet since address bar URI javascript:'s are not effective in recent (circa 2012) browsers
  • this effectively gives cross domain access but note:
    1. the javascript is notindigenous to a web page or site, meaning it's origin has a stateless nationality and thus intrinsically satisfies css (x-site scripting) and sop (same origin policy) immigration rules
    2. it is invoked manuallyvia the address bar or bookmarks AND
      the script is manuallyentered into those locations
  • 打开一个外国网址
  • 在那个外国网址 pg 上。地址栏输入javascript: ...URI
    它将继承与外部 URL
    NB相同的站点策略。由于地址栏 URIjavascript:在最近(大约 2012 年)浏览器中无效,因此可能需要将 javascript 标记为书签
  • 这有效地提供了跨域访问,但请注意:
    1. javascript不是网页或网站的本土化,这意味着它的来源具有无国籍国籍,因此本质上满足 css(x 站点脚本)和 sop(同源政策)移民规则
    2. 它是通过地址栏或书签手动调用的,
      并且脚本是手动输入到这些位置的

Thus any page, well almost, irregardless of origin, can be modified like:

因此,几乎任何页面,无论其来源如何,都可以修改为:

javascript:
  if(confirm("wipe out links & anchors?\n"+document.body.innerHTML))
     void(document.body.innerHTML=document.body.innerHTML.replace(/<a /g,"< a "))

(well almost ...
jar:file:///usr/lib/firefox/omni.ja!/chrome/toolkit/content/global/aboutSupport.xhtml
Mozilla's FF troubleshooting page and other jararchives are exceptions)

(几乎......
jar:file:///usr/lib/firefox/omni.ja!/chrome/toolkit/content/global/aboutSupport.xhtml
Mozilla 的 FF 故障排除页面和其他jar档案是例外)

As another example:
To routinely disable google's usurping of target pg. hits, change it's rwtfunction as follows:

再举一个例子:
定期禁用谷歌对目标 pg 的篡夺。点击,改变它的rwt功能如下:

javascript:void(rwt=function(unusurpURL){return unusurpURL})

and bookmark this as spay google(neuteralize google?) ie. it's "fixed".

并将其标记为spay googleneuteralize google?)即。它是“固定的”。

This bookmark is then clicked before any googlehits are clicked, so bookmarks of any of those hits are clean and not the mongrelized perverted aberrations that googlemade of them.

然后在单击任何google命中之前单击此书签,因此任何这些命中的书签都是干净的,而不是google由它们构成的杂种变态像差。

tests done with

测试完成

window.navigator.userAgent=
Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:11.0) Gecko/20100101 Firefox/11.0

It should be noted that addEventListenerin Mozilla only has a non-standard fourth, boolean parameter which,, if trueallows untrusted content triggers to be instantiated for foreign pages.

应该注意的是,addEventListener在 Mozilla 中只有一个非标准的第四个布尔参数,如果true允许不信任的内容触发器为外部页面实例化。

ref:
element.addEventListener | Document Object Model (DOM) | MDN:
Interaction between privileged and non-privileged pages | Code snippets | MDN:

参考:
element.addEventListener | 文档对象模型 (DOM) | MDN:
特权和非特权页面之间的交互| 代码片段 | MDN:

Bookmark:
Detecting the onload event of a window opened with window.open

书签:
检测使用 window.open 打开的窗口的 onload 事件

回答by Sebastiaan Ordelman

This did the trick for me; full example:

这对我有用;完整示例:

HTML:

HTML:

<a href="/my-popup.php" class="import">Click for my popup on same domain</a>

Javascript:

Javascript:

(function(){
    var doc = document;

    jQuery('.import').click(function(e){
        e.preventDefault();
        window.popup = window.open(jQuery(this).attr('href'), 'importwindow', 'width=500, height=200, top=100, left=200, toolbar=1');

        window.popup.onload = function() {
            window.popup.onbeforeunload = function(){
                doc.location.reload(true); //will refresh page after popup close
            }
        }
    });
})();

回答by Thevs

onloadevent handler must be inside popup's HTML <body>markup.

onload事件处理程序必须在弹出窗口的 HTML<body>标记内。

回答by Panu Logic

The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.

核心问题似乎是您正在打开一个窗口以显示其内容已缓存在浏览器中的页面。因此不会发生加载,因此不会发生加载事件。

One possibility could be to use the 'pageshow' -event instead, as described in:

一种可能性是使用 'pageshow' -event 代替,如下所述:

https://support.microsoft.com/en-us/help/3011939/onload-event-does-not-occur-when-clicking-the-back-button-to-a-previou

https://support.microsoft.com/en-us/help/3011939/onload-event-does-not-occur-when-clicking-the-back-button-to-a-previou

回答by Udo E.

First of all, when your firstinitial window is loaded, it is cached. Therefore, when creating a newwindow from the firstwindow, the contents of the new window are not loaded from the server, but are loaded from the cache. Consequently, no onloadevent occurs when you create the newwindow.

首先,当你的第一个初始窗口被加载时,它被缓存。因此,从第一个窗口创建窗口时,窗口的内容不是从服务器加载,而是从缓存加载。因此,创建窗口时不会发生任何事件。onload

However, in this case, an onpageshowevent occurs. It always occurs after the onloadevent and even when the page is loadedfrom cache. Plus, it now supported by all major browsers.

但是,在这种情况下,onpageshow会发生事件。它总是在onload事件之后发生,甚至在从缓存加载页面时也是如此。此外,现在所有主要浏览器都支持它。

 window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
 $(window.popup).onpageshow = function() {
     alert("Popup has loaded a page");
 };

The w3school websiteelaborates more on this:

w3school网站阐述更多内容:

The onpageshow event is similar to the onloadevent, except that it occurs after the onload event when the page first loads. Also, the onpageshowevent occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

onpageshow 事件与该onload事件类似,不同之处在于它发生在页面首次加载时的 onload 事件之后。此外,onpageshow每次加载页面时都会发生该事件,而从缓存加载页面时不会发生 onload 事件。