DIV CSS 佈局教程網

window.open 開啟的新視窗如何與父視窗雙向傳值
編輯:關於JavaScript     

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

傳值原理

  • 父視窗 → 子視窗:透過 URL 的查詢參數傳遞。
  • 子視窗 → 父視窗:透過呼叫父視窗上的全域函式傳遞。

父視窗 index.html

<!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&param2=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>

子視窗 window.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>

幾個關鍵點

  • window.opener:指向開啟目前視窗的父視窗參照,是反向溝通的唯一通道。
  • 第三個參數:用來控制新視窗的寬高、是否顯示工具列與捲軸等外觀。
  • 需要伺服器環境:上述範例請勿直接用 file:// 開啟,應透過本機或測試伺服器運行,否則會遇到安全限制。
  • 記得判空:實務上呼叫 window.opener 前最好確認其不為 null,例如使用者可能直接開啟子頁面網址。

若只是需要在同一頁面呈現選擇結果,改用 postMessage 搭配 iframe,或直接在同一頁以彈出層呈現,通常會比開新視窗更好維護。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved