1. 程式人生 > 實用技巧 >子頁面關閉時重新整理父頁面的解決方案

子頁面關閉時重新整理父頁面的解決方案

子頁面關閉時重新整理父頁面的解決方案

可用於:子頁面關閉時重新整理父頁面(重新載入資料)
因瀏覽器限制,父子頁面必須在同一域名下,請部署到Web伺服器之後測試

演示

演示效果:子頁面關閉或重新整理,均會導致父頁面的數字+1

父頁面father.html原始碼

<html>
    <head>
        <title>
            父頁面
        </title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script>
            function windowOpen(){
                window.open('son.html','子頁面');
            }
            </script>
    </head>
    <body>
        <h1 id="id">1</h1>
        <input type="button" value="子頁面" onclick="windowOpen()" />
    </body>
</html>

子頁面son.html原始碼

<html>
    <head>
        <title>
            子頁面
        </title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script>
			window.onbeforeunload = function(){
				var num = +window.opener.document.getElementById("id").innerHTML;
				window.opener.document.getElementById("id").innerHTML = 1+ num;
			}
        </script>
    </head>
    <body>
        <h1>我是子頁面</h1>
    </body>
</html>