【问题标题】:window.open opens pop up and not window - behavior inconsistentwindow.open 打开弹出窗口而不是窗口 - 行为不一致
【发布时间】:2014-08-23 00:27:55
【问题描述】:

在我的 javascript 代码中,我使用的是 window.open 方法,但行为完全不一致:根据我编写代码的方式,它将打开一个新选项卡或打开一个弹出窗口(被弹出窗口阻止)向上拦截器)。我不知道如何解决它感谢您的帮助。 html代码:

<a class='btn btn-success' target="_blank" onclick="quoteVisu(); return false;">Visualiser</a>

javascript代码:

function quoteVisu(){
  quoteCreate(1);
} 

quoteCreate 是一个带有 AJAX 调用的方法

function quoteCreate(num_function){
    var request=$.ajax({
    url: url_up,
    type: "POST",
    beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
    data: {q_param: {
             title: title, 
             total: total,
             list: list,
             client: idclient,
             tax_rate: tax_rate 
           }},
    success: function(data, textStatus, jqXHR) {
              if (num_function==1){request.done(goShow(data.quote_id))};
              if (num_function==0){request.done(goBack());}
            },
    dataType: "json"
    });
return true;
}

还有 goShow 方法:

function goShow(quote_id) {
    var url_visu="/visu_pdf/quote_visu."+quote_id
    window.open(url_visu, '_blank');
    return true;
 }

上面的代码给出了一个弹出窗口,这不是预期的行为。例如,如果我将 window.open 放在 quoteVisu 方法中,我将打开一个选项卡,而不是我想要的弹出窗口。但是如果我把它放在那里,我没有新窗口 url 所需的 JSON 的答案。

感谢您的帮助。

【问题讨论】:

  • You cannot control 是否弹出选项卡或窗口。这是一个本机实现。行为预计会在浏览器之间,甚至在其自身之间不一致。
  • 首先,我会从链接中删除target="_blank",这里没有意义。其次,由于异步 AJAX 调用,窗口的打开与实际的单击事件“解耦”,您可能会得到不同的行为 - 可能浏览器的反应不同。
  • 这似乎是问题,但没有解决方案的事实非常疯狂,因为我想这是一个常见问题......

标签: javascript ajax window.open


【解决方案1】:

根据 W3 HTML5 推荐,window.open 在调用时应该打开一个window[1] 但是,它只是说应该打开一个辅助的"browsing context"

Window 对象的 open() 方法提供了一种机制,用于导航现有浏览上下文或打开和导航辅助浏览上下文。

.open 方法确实提供了一个target 字段,您可以使用keywords from this set 来设置目标浏览内容:

             keyword                   ordinary effect

_blank new
_self current
_parent if there isn't a parent current
_parent if parent is also top parent/top
_parent if there is one and it's not top parent
_top if top is current current
_top if top is not current top

但是这并不能区分选项卡或窗口。

总而言之,无法控制是否会出现选项卡或窗口。这不是你能控制的事情。这是一个例子:http://jsfiddle.net/DerekL/0amrodLx/:

function openTab(name){
    open("http://en.wikipedia.com", name);
}

function timer(n){
    setTimeout(function(){ openTab(n); }, 1);
}

<a href="#" onclick="openTab('Wikipedia')">Open Tab</a>
<a href="#" onclick="timer('Wikipedia')">Open Tab With Timer</a>

没有计时器的链接似乎是一致的:每次在 Chrome 上打开一个标签。另一方面,带有计时器(异步)的那个永远不会一致(在 Chrome 上)。第一次打开一个窗口,下次我点击 Run 后,它会打开一个选项卡。无法确保它每次都打开一个选项卡。 (一般常见的浏览器会在被异步函数调用时打开一个窗口。)

【讨论】:

  • 哇,很好的答案,谢谢。如果我理解得很好,由于 ajax 呼叫应答的时间,我无法在这个问题上做任何事情,对吗?这很令人失望,但至少我不必再花时间调试了!
  • @fro 实际上没有解决方案,因为并非每个浏览器都有标签,并且一般建议尝试涵盖所有情况。由浏览器自己决定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多