JavaScript - 關閉當前窗口 - Scripts may close only the windows that were opened by them.


前言

有2個頁面

[
"Source.html",
"Target.html",
]

其中,Target.html頁面中還有幾個iframe頁面,

想實現的功能是,
1.點擊Source.html中的一個a標簽,跳轉到Target.html頁面,
2.在Target.html頁面操作完成之后,
點擊Target.html頁面中的關閉按鈕,關閉Target.html頁面


問題出在了,
跳轉到了Target.html頁面之后,
不在Target.html頁面的幾個iframe之間切換的話,
是可以點擊Target.html頁面中的關閉按鈕,關閉Target.html頁面.

但是,如果在Target.html頁面中切換幾個iframe,
此時在點擊Target.html頁面的關閉按鈕,是沒有辦法關閉Target.html頁面的.

網絡上標准答案

//第一種形式
window.opener = null;
window.open('', '_self', '');
window.close();


//第2種方式
var customWindow = window.open('', '_blank', '');
    customWindow.close();    


// 關閉頁面
closeCurrentPage() {
	const ua = window.navigator.userAgent;
	if (ua.indexOf('MSIE') > 0) {
		if (ua.indexOf('MSIE 6.0') > 0) {
			window.opener = null;
			window.close();
		} else {
			window.open('', '_top');
			window.top.close();
		}
	} else {
		window.opener = null;
		window.open('', '_self', '');
		window.close();
	}
}

使用了標准答案之后,控制台出現提示語

Scripts may close only the windows that were opened by them.

解決方案

我原來的


<a href="/Test.html?id=1" target="_blank">跳轉Target.html</a>

修改后的html


<a href="javascript:;" onclick="window.open('/Test.html?id=1', '_blank')"
跳轉Target.html
</a>

主要就是將原來的直接跳轉 href 修改為 window.open

摘抄文檔


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM