Javascript 如何打开然后关闭窗口而不会被阻止作为弹出窗口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10702344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open and then close a window without getting blocked as a popup?
提问by Yuval Cohen
I want to direct a customer in an e-commerce site to pay via Paypal's website. I would like the payment to be done in a new tab/window so the customer doesn't lose the current state of the web page he/she is at.
我想引导电子商务网站中的客户通过 Paypal 网站付款。我希望在新选项卡/窗口中完成付款,这样客户就不会丢失他/她所在网页的当前状态。
In order for the Paypal window to open without getting blocked, I am using an anchor with target="_blank". Which is working perfectly except for the fact, I can't close it after Paypal payment is done since window.close()
doesn't work for windows that were not opened via window.open()
.
为了打开 Paypal 窗口而不会被阻止,我使用了 target="_blank" 的锚点。除了事实之外,它工作得很好,我无法在 Paypal 付款完成后关闭它,因为window.close()
它不适用于未通过window.open()
.
How do I make it so it is BOTH not blocked as a popup AND I am able to close it with JS later on?
我如何使它不被阻止作为弹出窗口,并且我可以稍后用 JS 关闭它?
回答by T.J. Crowder
In order for the Paypal window to open without getting blocked, I am using an anchor with target="_blank".
为了打开 Paypal 窗口而不会被阻止,我使用了 target="_blank" 的锚点。
That's one option, but as long as you call window.open
from within the handler for a user-generated event (like click
), you can open pop-up windows. So just make sure you call window.open
from within a click
handler on the link (and then you can close it). Modern pop-up blockers (anything from the last several years) block pop-ups that aren't triggered by a user event, but allow ones that are.
这是一种选择,但只要您window.open
从处理程序中调用用户生成的事件(如click
),您就可以打开弹出窗口。所以只要确保你window.open
从click
链接的处理程序中调用(然后你可以关闭它)。现代弹出窗口阻止程序(过去几年的任何内容)阻止不是由用户事件触发的弹出窗口,但允许那些由用户事件触发的弹出窗口。
HTML:
HTML:
<p><a href="#" id="target">Click to open popup</a>; it will close automatically after five seconds.</p>
JavaScript:
JavaScript:
(function() {
document.getElementById("target").onclick = function() {
var wnd = window.open("http://stackoverflow.com");
setTimeout(function() {
wnd.close();
}, 5000);
return false;
};
})();