如果被窗口打开,新窗口的属性是什么?打开功能

What are the attributes of a new window, if opened by a window.open function?

本文关键字:窗口 属性 是什么 功能 新窗口 如果      更新时间:2023-09-26

如果我在<script></script>之间添加以下代码:

function test()
{
    var newWindow = window.open("https://stackoverflow.com/", "a", "width = 600,height = 400");
    document.write(newWindow.location.href);
    document.write(newWindow.innerWidth);
}
test();

输出是"about:blank"和0,虽然我认为它应该是"https://stackoverflow.com/"和600。我对这件事很困惑,等待一个解释。

AND:如果我想获得新窗口的URL,我该怎么做?多谢。

如果等待load事件,则可以异步捕获这些值:

var newWindow = window.open('http://www.stackoverflow.com', 'a', 'width=600,height=400')
newWindow.addEventListener('load', function () {
    console.log(newWindow.location.href);
    console.log(newWindow.innerWidth);
});

然而,正如James Thorpe指出的那样,这只会在新窗口与脚本运行的页面处于同一域时起作用,并且这是异步发生的,因此无论您试图通过使用document.write()完成什么都可能不起作用。