天天看點

window實作跨頁面傳輸資料

一般在js中定義變量的時候禁止使用name 作為屬性名 ,因為 我們可以使用window.name實作頁面的跨域傳輸

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script>
        window.name='var num = 100;';
    </script>
</body>
</html>      
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<button>點我</button>
    <script>
        //擷取另一個頁面的資料,則那個頁面必須被加載
        document.querySelector('button').onclick = function(eve){
            //定義iframe加載資料提供的頁面
            var iframe = document.createElement('iframe');
            iframe.src='anotherPage.html';
            iframe.style.display='none';
            document.body.appendChild(iframe);
            //加載成功後獲得資料
            iframe.onload = function (eve) {
                var e = eve||window.event;
                var t = e.target|| e.srcElement;
                var iframeWindowName =t.contentWindow.name;
                console.log(typeof iframeWindowName);
                eval(iframeWindowName);//将字元串轉為代碼
                console.log(num);
            }
        }
    </script>
</body>
</html>