我需要使用 window.open('...', '_blank'); 生成一个选项卡
然后,当用户单击按钮(按钮位于新选项卡中)时,我需要该选项卡自行关闭。
我可以控制这两个应用程序的代码库和服务器。
我尝试了以下方法:
在应用#1 中:
window.tab = window.open('http://localhost:5007', '_blank');
在应用#2 中:
function clickedButton() {
window.opener.tab.close();
}
不幸的是我遇到了安全异常: 错误:阻止源为“http://localhost:5007 ”的框架访问跨源框架。
如何解决此错误?无论如何,我可以使用这个库来克服这个问题吗? https://github.com/ternarylabs/porthole
最佳答案
我只是想在这里引用文档,仅供需要引用的人点击 W3C和 MDN .
function openWin() {
myWindow = window.open("", "myWindow", "width=200, height=100"); // Opens a new window
}
function closeWin() {
myWindow.close(); // Closes the new window
}
为了分解它,open
和 close
函数使用非常有用的参数,例如 URL
,当需要打开或关闭当前窗口,或者在您的情况下打开或关闭打开窗口。
一个实际的例子是 this堆栈溢出问题。 N
希望对您有帮助!
编辑
要回答OP的编辑问题:如果是在打开的窗口上触发事件,您可以在新窗口上有一个事件处理程序来触发window.close()
像这样:
$('#anElementId').click(function() { window.opener.$('body').trigger('theCloseEvent', anyPassedData); })
但是,如果您确实可以控制新选项卡,因为它会指向您可以控制其代码库的 URL,那么只需触发一个事件即可,您可以在窗口打开时触发该事件加载,或者单击按钮后...就像这样:
HTML
<button id="close-window">Close me</button>
Javascript/jQuery:
$(document).ready(function(){
$("#close-window").click(function(){
alert("ok");
window.close();
});
});
编辑#2
为了进一步扩展OP的编辑,我想在此处包含一个在尝试触发打开的窗口自行关闭时很容易遇到的问题。
引自How can I close a browser window without receiving the “Do you want to close this window” prompt? :
Scripts are not allowed to close a window that a user opened. This is considered a security risk. Though it isn't in any standard, all browser vendors follow this (Mozilla docs). If this happens in some browsers, it's a security bug that (ideally) gets patched very quickly.
None of the hacks in the answers on this question work any longer, and if someone would come up with another dirty hack, eventually it will stop working as well.
I suggest you don't waste energy fighting this and embrace the method that the browser so helpfully gives you — ask the user before you seemingly crash their page.
换句话说,除非您的网页脚本可以控制打开的窗口,否则您应该/不能关闭该窗口。这是因为运行 window.close
的脚本无法控制打开的窗口。
编辑#3
我知道这么多编辑!但我是在日常生活中回答这个问题的,所以请耐心等待。要回答 porthole.js 问题,应该更可能用它做一些事情,但是您需要意识到您正在使用 iframe。
使用网站与使用iframe之间存在显着差异,其中iframe是小部件,网站(包括迷你网站)有一个URL。在安全性和沙箱方面也有很多考虑因素,如 portholejs demo here 中所示。 。这种差异也导致您无法按照最初想要的方式使用不同的网站。
我的建议是评估您在实现方面的选择:网站到网站还是网站到小部件。
祝你好运!
关于javascript - porthole.js - 如何关闭使用 window.open() 打开的选项卡,但从新选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33263105/