gpt4 book ai didi

javascript - jQuery - 使用 Window.Open() 防止弹出窗口阻止程序;

转载 作者:行者123 更新时间:2023-12-02 14:18:58 24 4
gpt4 key购买 nike

如果我使用 jQuery 在新窗口中打开,如何避免浏览器受到弹出窗口阻止程序的影响。我一直在谷歌上搜索这个问题,但仍然坚持下去。这是我编写的代码,

$(document).ready(function(){
$('#newLink').click(function(event){
event.preventDefault();
var page = $(this).attr('href');
$.post(page,
{
pr_no : pr_no
})
.done(function(data){
window.open(page, "MsgWindow", "width=800,height=800");
});
});

最佳答案

弹出窗口拦截器通常只允许在处理用户事件(如单击)期间使用 window.open。在您的情况下,您稍后调用 window.open,而不是在事件期间,因为 $.getJSON 是异步的。

您有两个选择:

做点别的事情,而不是window.open。使 ajax 调用同步,这是您通常应该避免的事情,就像瘟疫一样,因为它会锁定浏览器的 UI。 $.getJSON 相当于:

$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});

...因此您可以通过将参数映射到上面并添加 async: false 来使 $.getJSON 调用同步:

$.ajax({
url: "redirect/" + pageId,
async: false,
dataType: "json",
data: {},
success: function(status) {
if (status == null) {
alert("Error in verifying the status.");
} else if(!status) {
$("#agreement").dialog("open");
} else {
window.open(redirectionURL);
}
}
});

再次强调,如果您能找到任何其他方法来实现您的目标,我不提倡同步 ajax 调用。但如果你做不到,那你就去吧。

以下是由于异步调用而导致测试失败的代码示例:

实例 |实时源(由于 JSBin 的更改,实时链接不再有效)

jQuery(function($) {
// This version doesn't work, because the window.open is
// not during the event processing
$("#theButton").click(function(e) {
e.preventDefault();
$.getJSON("http://jsbin.com/uriyip", function() {
window.open("http://jsbin.com/ubiqev");
});
});
});

这是一个使用同步调用的有效示例:

实例 |实时源(由于 JSBin 的更改,实时链接不再有效)

jQuery(function($) {
// This version does work, because the window.open is
// during the event processing. But it uses a synchronous
// ajax call, locking up the browser UI while the call is
// in progress.
$("#theButton").click(function(e) {
e.preventDefault();
$.ajax({
url: "http://jsbin.com/uriyip",
async: false,
dataType: "json",
success: function() {
window.open("http://jsbin.com/ubiqev");
}
});
});
});

关于javascript - jQuery - 使用 Window.Open() 防止弹出窗口阻止程序;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38812311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com