window.open 后的 Javascript 调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10797266/
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-24 02:57:43  来源:igfitidea点击:

Javascript Call function after window.open

javascriptloadwindow

提问by pm13

I'm trying to call a function after my window.open function has fully loaded.

我试图在 window.open 函数完全加载后调用一个函数。

However, using the onload function is being called too soon. The URL that's being hit opens an excel spreadsheet and can take from 2 secs to 1 min to download.

但是,使用 onload 函数被调用得太快了。被点击的 URL 会打开一个 Excel 电子表格,下载可能需要 2 秒到 1 分钟。

The onload function is being called as soon as the window.open function has been called. However, I need to know when the excel doc has been opened - not when the URL was hit.

只要调用 window.open 函数,就会调用 onload 函数。但是,我需要知道何时打开 excel 文档 - 而不是在点击 URL 时。

I've tried setting an interval but that's not being called:

我试过设置一个间隔,但没有被调用:

w = window.open(url,'_parent',false);   

w.onload = function(){
    console.log('here');
    setInterval(function(){
        alert('Hi');
    },10);

回答by Denys Séguret

First note that in order to do this without being blocked because of cross-domain restrictions (or without having to parameterize CORS headers on your server), you must :

首先请注意,为了不因跨域限制而被阻止(或不必在服务器上参数化 CORS 标头),您必须:

  • serve both your main page and the popup content (your excel file) from the same domain, and the same port
  • open your main page in http://and not in file://
  • 从同一个域和同一个端口提供您的主页和弹出内容(您的 excel 文件)
  • 打开你的主页http://而不是file://

If those conditions are respected, the best solution is to use jquery as its loadfunction waits "until all assets such as images have been completely received" :

如果满足这些条件,最好的解决方案是使用 jquery,因为它的加载函数会等待“直到所有资产(例如图像)都已完全收到”:

<html>
    <head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
<body>
<script>
var popup = window.open('popup.html');
$(popup.document).load(function() {
    alert('loaded');
    // do other things
});
</script>
</body>
</html>

Be careful with your global scheme : each browser/configuration may do something different when you think they "open" the file. There's no way to detect with a simple openif they decided to dismiss it, hadn't the proper plugin, simply downloaded it.

小心你的全局方案:当你认为每个浏览器/配置“打开”文件时,它们可能会做不同的事情。open如果他们决定关闭它,没有合适的插件,只需下载它,就无法通过简单的方法检测到。