如果我在<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()
完成什么都可能不起作用。