[英]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.