opener即誰打開我的,比如A頁面利用window.open彈出了B頁面窗口,那麼A頁面所在窗口就是B頁面的opener,在B頁面通過opener對象可以訪問A頁面。
parent表示父窗口,比如一個A頁面利用iframe或frame調用B頁面,那麼A頁面所在窗口就是B頁面的parent。在JS中,window.opener只是對彈出窗口的母窗口的一個引用。比如:a.html中,通過點擊按鈕等方式window.open出一個新的窗口b.html。那麼在b.html中,就可以通過window.opener(省略寫為opener)來引用a.html,包括a.html的document等對象,操作a.html的內容。
假如這個引用失敗,那麼將返回null。所以在調用opener的對象前,要先判斷對像是否為null,否則會出現“對象為空或者不存在”的JS錯誤。
示例:
aa.html
複製代碼代碼如下:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<body>
<span id="name"></span>
<input type="button" " value="彈窗" onclick="window.open('bb.html')" />
</body>
</html
bb.html
複製代碼代碼如下:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<body>
<input type="text" id="inputValue"/>
<input type="button" value="添加" onclick="window.opener.document.getElementById('name').innerHTML=inputValue.value"/>
</body>
</html>
window.opener 返回的是創建當前窗口的那個窗口的引用,比如點擊了aa.htm上的一個鏈接而打開了bb.htm,然後我們打算在bb.htm上輸入一個值然後賦予aa.htm上的一個id為“name”的textbox中,就可以
寫為:
window.opener.document.getElementById("name").value = "輸入的數據";
window.opener.document.getElementById("name").innerHTML= "輸入的數據";