[英]Not able to fetch the URL / location of the pop-up window
有没有一种方法可以获取弹出窗口的URL /位置?
码:
<html>
<head>
<script>
function openWin()
{
myWindow=window.open('http://www.google.com','','width=200,height=100');
console.debug(myWindow.location.href);
console.debug(window.location.href);
}
</script>
</head>
<body>
<input type="button" value="Open window" onclick="openWin()" />
</body>
</html>
第一个控制台显示以下about:blank
当第二个控制台打印当前页面的URL(即上面代码的URL时,它不打印弹出窗口的URL)
为什么第一个控制台不打印位置(即http://www.google.com )?
谁能帮我这个忙吗?
提前致谢。
正如@ Hg3所说,您无法访问myWindow
location.href
。 window.open
返回一个空的DOMWindow
。
但是,您可以覆盖window.open
并维护所有已打开窗口的简单数组。
//override window.open
var windows = [];
window._open = window.open;
window.open = function(url, name, params){
windows.push(name, url);
return window._open(url, name, params)
}
//function return href by name
function hrefByName(name) {
var index=(windows.indexOf(name));
return (index>-1) ? windows[index+1] : 'undefined';
}
//modified openWin function
function openWin(url, name) {
var params='width=200,height=100';
window.open(url, name, params);
//test, ouput current url and the windows array
console.log(hrefByName(name));
console.log(windows);
}
测试标记:
<input type="button" value="google" onclick="openWin('http://google.com', 'google')" />
<input type="button" value="bing" onclick="openWin('http://bing.com', 'bing')" />
<input type="button" value="stackoverflow" onclick="openWin('http://stackoverflow.com', 'stackoverflow')" />
当然,我想您有一个带有动态生成的URL的设置-只需构建随机名称或传递唯一数字作为名称即可。
因为浏览器安全性阻止您从与脚本不在同一域中的任何窗口获取URL。 因此,如果您的代码在example.com上运行,则只能获取也在example.com上的任何窗口的URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.