2011-01-09 280 views
1

是否可以檢查相同的窗口是否已打開?Javascript:檢查重複打開的窗口

例如,我通過JavaScript打開了一個窗口。

我可以檢查是否在另一個頁面上通過JavaScript打開?

只是想專注於頁面,如果它已被打開,以避免重複的窗口。

感謝)

回答

2

window.open()方法。您必須指定窗口的名稱作爲第二個參數。如果已經有一個帶有該名稱的窗口,則新URL將在已有窗口中打開,請參見http://www.w3schools.com/jsref/met_win_open.asp

如果您確實想檢查,如果窗口是由您自己的腳本打開的,那麼您必須保持到打開的窗口中的引用在一個全局變量或喜歡與

var myOpenedWindow = myOpenedWindow || window.open(URL, "MyNewWindow"); 

創建它,你也可以在方法封裝這一行爲:

var myOpenWindow = function(URL) { 
    var myOpenedWindow = myOpenedWindow || window.open(URL, "MyNewWindow"); 
    myOpenedWindow.location.href= URL; 
    myOpenedWindow.focus(); 
} 

,並調用該函數myOpenWindow('http://www.example.com/');

+0

感謝隊友對這個解決方案打開一個URL;) – Somebody 2011-01-10 10:58:16

1

如果您有父母 - 子窗口,那麼這裏有一個解決方案,可以讓您檢查是否從啓動子窗口的父窗口打開子窗口。這將帶來一個 焦點子窗口無需重新加載它的數據:

<script type="text/javascript"> 
    var popWin; 
    function popPage(url) 
    { 
     if (popWin &! popWin.closed && popWin.focus){ 
      popWin.focus(); 
     } else { 
      popWin = window.open(url,'','width=800,height=600'); 
     } 
    } 
</script> 

    <a href="http://www.xzy.com" 
onclick="popPage(this.href);return false;">link</a> 

一兩件事--- ::如果用戶刷新父窗口,它可能失去了所有的 引用任何子窗口它可能已經打開。

希望這有助於讓我知道輸出。

0

這將幫助,如果你想從一個鏈接

var Win=null; 
function newTab(url){ 
//var Win; // this will hold our opened window 

// first check to see if the window already exists 
if (Win != null) { 
// the window has already been created, but did the user close it? 
// if so, then reopen it. Otherwise make it the active window. 
if (!Win.closed) { 
    Win.close(); 
// return winObj; 
} 

// otherwise fall through to the code below to re-open the window 
} 

// if we get here, then the window hasn't been created yet, or it 
// was closed by the user. 
Win = window.open(url); 

return Win; 

} 
newTab('index.html');