在 Window 加载时做点什么

Do Something When Window Loads

我试图在 window 加载时打开一个警告框。这是我拥有的:

var imawindow = window.open("http://google.com");
imawindow.onload() = function () {
    alert("hey");
}

我做错了什么?提前致谢!

你不应该在赋值之前执行它。删除 ()。如果您想在呼叫者上呼叫 alert,请使用 window.opener:

imawindow.onload =  function () {
    window.opener.alert("hey");
}

这应该遵守同域政策。调用 window,应该是您域中的相关页面。不像你可以从 http://www.facebook.com/ 调用 http://www.google.com/。但是你可以从 hello.html 上的 index.html 调用它,前提是 index.htmlhello.html 来自同一个域,比如 http://example.com/index.htmlhttp://example.com/hello.html

我想提一下,它不适用于跨域。

如果您在同一域中打开新页面,您可以通过以下方式实现:

var imawindow = window.open("samedomainpage.html");
imawindow .addEventListener('load', functionToCall, false);

出于安全原因,对于跨域,这将不起作用。阅读更多相关信息 here