彈窗實作有幾種常見路線:用 div 模擬、用 iframe 內嵌,或者直接用瀏覽器原生的 window.open() 開一個新視窗。本文要談的是第三種,示範兩個視窗之間如何雙向傳遞資料。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<button id="test">按鈕</button>
<script>
var test = document.getElementById('test');
test.onclick = function() {
window.open('./window.html?param1=name¶m2=password', '_blank',
'width=960,height=650,menubar=no,toolbar=no,location=no,
directories=no,status=no,scrollbars=yes,resizable=yes');
};
// 對外開放的全域函式,供子視窗回傳資料時呼叫
window.getContent = function(tx) {
document.getElementById('content').innerText = tx;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<select name="" id="city">
<option value="shanghai">上海</option>
<option value="hangzhou">杭州</option>
</select>
<script>
// 解析網址中 ? 後面的參數
var params = location.href.substring(location.href.lastIndexOf('?')+1).split('&');
document.getElementById('content').innerText = params;
var city = document.getElementById('city');
city.onchange = function() {
// 透過 opener 取得開啟它的父視窗,再呼叫其全域函式
window.opener.getContent(city.value);
}
</script>
</body>
</html>
file:// 開啟,應透過本機或測試伺服器運行,否則會遇到安全限制。window.opener 前最好確認其不為 null,例如使用者可能直接開啟子頁面網址。若只是需要在同一頁面呈現選擇結果,改用 postMessage 搭配 iframe,或直接在同一頁以彈出層呈現,通常會比開新視窗更好維護。