2011-03-22 107 views
0

我想獲得已打開窗口的窗口對象,並且我不想在預期的窗口關閉時打開新窗口。如何使用java腳本或jQuery獲取瀏覽器窗口對象

我嘗試以下選項:

var windowObj = window.open('','windowName', ''); 

但是它會打開一個新的窗口,當窗口預期不存在/關閉。

請建議我使用JavaScript或jQuery獲取窗口對象。

+1

你的意思是已經打開的窗口,還是你的意思是另一個被命名的開窗口? – Eero 2011-03-22 13:36:23

回答

0

你不能。調用window.open函數時,您需要保留打開的窗口的引用。否則無法獲得參考。

一個解決方案就是隻在前一個關閉時創建一個新窗口,否則就重新使用它。例如:

var _childWin = null; 

function getChildWin() { 
    if (_childWin == null || _childWin.closed) { 
     _childWin = window.open(...); 
    } 
    return _childWin; 
} 
0

剛剛var windowObj = window;怎麼樣?你甚至不需要把它分配給你自己的變量。

0

實際上有兩個途徑獲得的「窗口」

var thisWindow = window; // window script resides 
var newOpenWindow = window.open(parameters for window here);// window opened 

對於newOpenWindow,您可以查看之前打開它,如果它存在(沒有你做的「開放」已經基本)通過查找假值

if (newOpenWindow) // if true it is open 

其他窗口,你就不能因爲他們是出了腳本的範圍窗口/瀏覽器實例中,一旦被打開,從劇本的角度檢測。

還有一個「包含的窗口」,它實際上是一個iframe中的文檔,這完全是另一回事。

編輯:舉例說明窗口交互

創建一個名爲TestCallBack.html

在兩個窗口

注意jQuery的一個子窗口。

顯示窗之間有一些功能上的相互作用(從孩子路過,窗口和新的Windows文檔的jQuery對象):

子窗口的佈局:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>iamchild</title> 
    <script src="JS/jQuery/jquery.js" type="text/javascript"></script> 
    <script src="JS/TestCallBack.js" type="text/javascript"></script> 
</head> 
<body> 
    Howdy 
    <div id="achildy">HereIBe 
    <div id="inchildy"> 
     I am childy text 
    </div> 
    </div> 
</body> 
</html> 

的TestCallBack.js的文本文件:

var ct; 
function childCallBack(passstuff) 
{ 
    alert('ct:"' + ct + '" CHILD GOT:(' + passstuff + ")"); 
    return ct; 
}; 
$(document).ready(function() 
{ 
    ct = $("#achildy").text(); 
    window.opener.logNewWindow(window, $(document)); 
}); 

在父窗口JavaScript打開子窗口:(和功能的子調用)

function logNewWindow(newWindow, JQnewWindowDoc) 
{ 
    var mychildText = JQnewWindowDoc.text();//all the child doc text 
    var innerChildText = $("#inchildy", JQnewWindowDoc).text();// one element text 
    var gotback = newWindow.childCallBack("CHILD TEXT:" + mychildText + " INNER:" + innerChildText); 
    alert("GOT:" + gotback); //child sent me this text from childCallBack 
}; 

var AWindow = window.open("TestCallBack.html"); 
相關問題