【问题标题】:Javascript GET request before window.open prevents target _blankwindow.open 之前的 Javascript GET 请求阻止目标 _blank
【发布时间】:2015-03-04 11:45:56
【问题描述】:

我想在 javascript 中制作点击记录器,然后在新选项卡中打开请求的链接。当您点击 google 搜索结果时,发生的情况几乎相同。

这段代码应该可以做到,而且几乎可以做到。唯一的问题是 window.open 不会打开新选项卡。相反,它会在同一选项卡中打开页面。如果我从代码中删除 xmlhttp 调用,则尊重“_blank”。为什么 window.open 之前的 xmlhttp 请求阻止了 '_blank' 生效?

recordClick = function(t, id) {
  var clickurl = "http://www.example.com";
  if(clickurl != undefined && clickurl.length > 0) {
    xmlhttp.open("GET",clickurl,false);
    xmlhttp.send();
  }
  if(id > 0) {
    window.open("http://www.example.com/click/"+id, '_blank');
  } else {
    window.open(t, '_blank');
  }
}

更新

这很容易。添加var xmlhttp = new XMLHttpRequest(); 即可解决。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用 JavaScript 而不是 target 打开新窗口:

    /*
     * Create the new window
     */
    
    
    function openInNewWindow() {
        // Change "_blank" to something like "newWindow" to load all links in the same new window
    
        var newWindow = window.open(this.getAttribute('href'), '_blank');
        newWindow.focus();
        return false;
    }
    
    /*
     * Add the **openInNewWindow** function to the **onclick** event of links with a class name of "non-html"
     */
    
    function getNewWindowLinks() {
        if (document.getElementById && document.createElement && document.appendChild) {
            var strNewWindowAlert = " (opens in a new window)";
            var objWarningText;
            var strWarningText;
            var link;
            var links = document.getElementsByTagName('a');
            for (var i = 0; i < links.length; i++) {
                    link = links[i];
                    // Find all links with a class name of "non-html"
                    if (/\bnon\-html\b/.exec(link.className)) {
                        // Create an em element containing the new window warning text and insert it after the link text
                        objWarningText = document.createElement("em");
                        strWarningText =     document.createTextNode(strNewWindowAlert);
                        objWarningText.appendChild(strWarningText);
                        link.appendChild(objWarningText);
                        link.onclick = openInNewWindow;
                      }
            }
        objWarningText = null;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 2016-09-08
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多