JavaScript - 关闭当前窗口 - Scripts may close only the windows that were opened by them.
<h3 id="前言">前言</h3><p>有2个页面</p>
<pre><code class="language-json">[
"Source.html",
"Target.html",
]
</code></pre>
<p>其中,<code>Target.html</code>页面中还有几个iframe页面,</p>
<p>想实现的功能是,<br>
1.点击<code>Source.html</code>中的一个<code>a</code>标签,跳转到<code>Target.html</code>页面,<br>
2.在<code>Target.html</code>页面操作完成之后,<br>
点击<code>Target.html</code>页面中的关闭按钮,关闭<code>Target.html</code>页面</p>
<hr>
<p>问题出在了,<br>
跳转到了<code>Target.html</code>页面之后,<br>
不在<code>Target.html</code>页面的几个iframe之间切换的话,<br>
是可以点击<code>Target.html</code>页面中的关闭按钮,关闭<code>Target.html</code>页面.</p>
<p>但是,如果在<code>Target.html</code>页面中切换几个iframe,<br>
此时在点击<code>Target.html</code>页面的关闭按钮,是没有办法关闭<code>Target.html</code>页面的.</p>
<h3 id="网络上标准答案">网络上标准答案</h3>
<pre><code class="language-JavaScript">//第一种形式
window.opener = null;
window.open('', '_self', '');
window.close();
//第2种方式
var customWindow = window.open('', '_blank', '');
customWindow.close();
</code></pre>
<pre><code class="language-JavaScript">
// 关闭页面
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();
}
}
</code></pre>
<h3 id="使用了标准答案之后控制台出现提示语">使用了标准答案之后,控制台出现提示语</h3>
<pre><code class="language-JavaScript">Scripts may close only the windows that were opened by them.
</code></pre>
<h3 id="解决方案">解决方案</h3>
<p>我原来的</p>
<pre><code class="language-html">
<a href="/Test.html?id=1" target="_blank">跳转Target.html</a>
</code></pre>
<p>修改后的html</p>
<pre><code class="language-html">
<a href="javascript:;" onclick="window.open('/Test.html?id=1', '_blank')"
跳转Target.html
</a>
</code></pre>
<p>主要就是将原来的直接跳转 <code>href</code> 修改为 <code>window.open</code></p>
<h3 id="摘抄文档">摘抄文档</h3>
<ul>
<li>stackoverflow.window.close() doesn't work - Scripts may close only the windows that were opened by it</li>
<li>好记的博客.JavaScript关闭当前页</li>
<li>pencilcool.关闭浏览器当前窗口问题:js方法window.close()不兼容谷歌浏览器</li>
</ul><br><br>
来源:https://www.cnblogs.com/love-zf/p/15085642.html
頁:
[1]