首页 文章

使用JavaScript在新选项卡(而不是新窗口)中打开URL

提问于
浏览
1702

我试图在新选项卡中打开URL,而不是弹出窗口 . 我已经看到相关的问题,其中的回答看起来像:

window.open(url,'_blank');
window.open(url);

但是它们都没有为我工作,浏览器仍然试图打开一个弹出窗口 .

27 回答

  • 745

    我使用以下,它运作良好!

    window.open(url, '_blank').focus();
    
  • 3

    某种程度上website可以做到 . (我没有时间从这个烂摊子中提取它,但这是代码)

    if (!Array.prototype.indexOf)
        Array.prototype.indexOf = function(searchElement, fromIndex) {
            if (this === undefined || this === null)
                throw new TypeError('"this" is null or not defined');
            var length = this.length >>> 0;
            fromIndex = +fromIndex || 0;
            if (Math.abs(fromIndex) === Infinity)
                fromIndex = 0;
            if (fromIndex < 0) {
                fromIndex += length;
                if (fromIndex < 0)
                    fromIndex = 0
            }
            for (; fromIndex < length; fromIndex++)
                if (this[fromIndex] === searchElement)
                    return fromIndex;
            return -1
        };
    (function Popunder(options) {
        var _parent, popunder, posX, posY, cookieName, cookie, browser, numberOfTimes, expires = -1,
            wrapping, url = "",
            size, frequency, mobilePopupDisabled = options.mobilePopupDisabled;
        if (this instanceof Popunder === false)
            return new Popunder(options);
        try {
            _parent = top != self && typeof top.document.location.toString() === "string" ? top : self
        } catch (e) {
            _parent = self
        }
        cookieName = "adk2_popunder";
        popunder = null;
        browser = function() {
            var n = navigator.userAgent.toLowerCase(),
                b = {
                    webkit: /webkit/.test(n),
                    mozilla: /mozilla/.test(n) && !/(compatible|webkit)/.test(n),
                    chrome: /chrome/.test(n),
                    msie: /msie/.test(n) && !/opera/.test(n),
                    firefox: /firefox/.test(n),
                    safari: /safari/.test(n) && !/chrome/.test(n),
                    opera: /opera/.test(n)
                };
            b.version = b.safari ? (n.match(/.+(?:ri)[\/: ]([\d.]+)/) || [])[1] : (n.match(/.+(?:ox|me|ra|ie)[\/:]([\d.]+)/) || [])[1];
            return b
        }();
        initOptions(options);
    
        function initOptions(options) {
            options = options || {};
            if (options.wrapping)
                wrapping = options.wrapping;
            else {
                options.serverdomain = options.serverdomain || "ads.adk2.com";
                options.size = options.size || "800x600";
                options.ci = "3";
                var arr = [],
                    excluded = ["serverdomain", "numOfTimes", "duration", "period"];
                for (var p in options)
                    options.hasOwnProperty(p) && options[p].toString() && excluded.indexOf(p) === -1 && arr.push(p + "=" + encodeURIComponent(options[p]));
                url = "http://" + options.serverdomain + "/player.html?rt=popunder&" + arr.join("&")
            }
            if (options.size) {
                size = options.size.split("x");
                options.width = size[0];
                options.height = size[1]
            }
            if (options.frequency) {
                frequency = /([0-9]+)\/([0-9]+)(\w)/.exec(options.frequency);
                options.numOfTimes = +frequency[1];
                options.duration = +frequency[2];
                options.period = ({
                    m: "minute",
                    h: "hour",
                    d: "day"
                })[frequency[3].toLowerCase()]
            }
            if (options.period)
                switch (options.period.toLowerCase()) {
                    case "minute":
                        expires = options.duration * 60 * 1e3;
                        break;
                    case "hour":
                        expires = options.duration * 60 * 60 * 1e3;
                        break;
                    case "day":
                        expires = options.duration * 24 * 60 * 60 * 1e3
                }
            posX = typeof options.left != "undefined" ? options.left.toString() : window.screenX;
            posY = typeof options.top != "undefined" ? options.top.toString() : window.screenY;
            numberOfTimes = options.numOfTimes
        }
    
        function getCookie(name) {
            try {
                var parts = document.cookie.split(name + "=");
                if (parts.length == 2)
                    return unescape(parts.pop().split(";").shift()).split("|")
            } catch (err) {}
        }
    
        function setCookie(value, expiresDate) {
            expiresDate = cookie[1] || expiresDate.toGMTString();
            document.cookie = cookieName + "=" + escape(value + "|" + expiresDate) + ";expires=" + expiresDate + ";path=/"
        }
    
        function addEvent(listenerEvent) {
            if (document.addEventListener)
                document.addEventListener("click", listenerEvent, false);
            else
                document.attachEvent("onclick", listenerEvent)
        }
    
        function removeEvent(listenerEvent) {
            if (document.removeEventListener)
                document.removeEventListener("click", listenerEvent, false);
            else
                document.detachEvent("onclick", listenerEvent)
        }
    
        function isCapped() {
            cookie = getCookie(cookieName) || [];
            return !!numberOfTimes && +numberOfTimes <= +cookie[0]
        }
    
        function pop() {
            var features = "type=fullWindow, fullscreen, scrollbars=yes",
                listenerEvent = function() {
                    var now, next;
                    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
                        if (mobilePopupDisabled)
                            return;
                    if (isCapped())
                        return;
                    if (browser.chrome && parseInt(browser.version.split(".")[0], 10) > 30 && adParams.openNewTab) {
                        now = new Date;
                        next = new Date(now.setTime(now.getTime() + expires));
                        setCookie((+cookie[0] || 0) + 1, next);
                        removeEvent(listenerEvent);
                        window.open("javascript:window.focus()", "_self", "");
                        simulateClick(url);
                        popunder = null
                    } else
                        popunder = _parent.window.open(url, Math.random().toString(36).substring(7), features);
                    if (wrapping) {
                        popunder.document.write("<html><head></head><body>" + unescape(wrapping || "") + "</body></html>");
                        popunder.document.body.style.margin = 0
                    }
                    if (popunder) {
                        now = new Date;
                        next = new Date(now.setTime(now.getTime() + expires));
                        setCookie((+cookie[0] || 0) + 1, next);
                        moveUnder();
                        removeEvent(listenerEvent)
                    }
                };
            addEvent(listenerEvent)
        }
        var simulateClick = function(url) {
            var a = document.createElement("a"),
                u = !url ? "data:text/html,<script>window.close();<\/script>;" : url,
                evt = document.createEvent("MouseEvents");
            a.href = u;
            document.body.appendChild(a);
            evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
            a.dispatchEvent(evt);
            a.parentNode.removeChild(a)
        };
    
        function moveUnder() {
            try {
                popunder.blur();
                popunder.opener.window.focus();
                window.self.window.focus();
                window.focus();
                if (browser.firefox)
                    openCloseWindow();
                else if (browser.webkit)
                    openCloseTab();
                else
                    browser.msie && setTimeout(function() {
                        popunder.blur();
                        popunder.opener.window.focus();
                        window.self.window.focus();
                        window.focus()
                    }, 1e3)
            } catch (e) {}
        }
    
        function openCloseWindow() {
            var tmp = popunder.window.open("about:blank");
            tmp.focus();
            tmp.close();
            setTimeout(function() {
                try {
                    tmp = popunder.window.open("about:blank");
                    tmp.focus();
                    tmp.close()
                } catch (e) {}
            }, 1)
        }
    
        function openCloseTab() {
            var ghost = document.createElement("a"),
                clk;
            document.getElementsByTagName("body")[0].appendChild(ghost);
            clk = document.createEvent("MouseEvents");
            clk.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
            ghost.dispatchEvent(clk);
            ghost.parentNode.removeChild(ghost);
            window.open("about:blank", "PopHelper").close()
        }
        pop()
    })(adParams)
    
  • -1

    这项工作对我来说,只是阻止事件,将URL添加到 <a> tag 然后触发 tag 上的click事件 .

    Js
    $('.myBtn').on('click', function(event) {
            event.preventDefault();
            $(this).attr('href',"http://someurl.com");
            $(this).trigger('click');
    });
    HTML
    <a href="#" class="myBtn" target="_blank">Go</a>
    
  • -1

    window.open无法在所有浏览器的新选项卡中可靠地打开弹出窗口

    Different browsers implement the behavior of window.open in different ways, especially with regard to a user's browser preferences. 您不能指望 window.open 在所有Internet Explorer,Firefox和Chrome中都有相同的行为,因为它们处理用户浏览器首选项的方式不同 .

    例如,Internet Explorer(11)用户可以选择在新窗口或新选项卡中打开弹出窗口, you cannot force Internet Explorer 11 users to open popups in a certain way through window.open ,如Quentin's answer中所提到的 .

    至于Firefox(29)用户,使用 window.open(url, '_blank') depends on their browser's tab preferences, 虽然你仍然可以通过指定宽度和高度强制它们在新窗口中打开弹出窗口(参见下面的"What About Chrome?"部分) .

    示范

    转到浏览器的设置并将其配置为在新窗口中打开弹出窗口 .

    Internet Explorer(11)

    Internet Explorer settings dialog 1

    Internet Explorer tab settings dialog

    测试页面

    设置Internet Explorer(11)以在新窗口中打开弹出窗口,如上所示,使用以下测试页来测试 window.open

    <!DOCTYPE html>
    <html>
      <head>
        <title>Test</title>
      </head>
    
      <body>
        <button onclick="window.open('https://stackoverflow.com/q/4907843/456814');">
          <code>window.open(url)</code>
        </button>
        <button onclick="window.open('https://stackoverflow.com/q/4907843/456814', '_blank');">
          <code>window.open(url, '_blank')</code>
        </button>
      </body>
    </html>
    

    观察弹出窗口是否已打开 in a new window, not a new tab.

    您还可以在Firefox(29)中测试上面的代码段,并将其选项卡首选项设置为新窗口,并查看相同的结果 .

    Chrome怎么样?它实现了window.open与Internet Explorer(11)和Firefox(29)不同 .

    我不是百分百肯定,但看起来Chrome(版本 34.0.1847.131 m )似乎没有任何设置可供用户选择是否在新窗口或新标签中打开弹出窗口(如Firefox和Internet)资源管理器) . 我查了the Chrome documentation for managing pop-ups,但它没有提到任何关于那种事情 .

    此外, once again, different browsers seem to implement the behavior of window.open differently. 在Chrome和Firefox中, specifying a width and height will force a popup, 即使用户已将Firefox(29)设置为在新标签页中打开新窗口(如JavaScript open in a new window, not tab的答案中所述):

    <!DOCTYPE html>
    <html>
      <head>
        <title>Test</title>
      </head>
    
      <body>
        <button onclick="window.open('https://stackoverflow.com/q/4907843/456814', 'test', 'width=400, height=400');">
          <code>window.open(url)</code>
        </button>
      </body>
    </html>
    

    但是, will always open a new tab in Internet Explorer 11 if users set tabs as their browser preferences, 上面的相同代码片段甚至没有指定宽度和高度将强制为它们弹出一个新窗口 .

    所以 window.open 在Chrome中的行为似乎是在 onclick 事件中使用时在新选项卡中打开弹出窗口,从浏览器控制台(as noted by other people)使用时在新窗口中打开它们,并在指定时在新窗口中打开它们宽度和高度 .

    摘要

    Different browsers implement the behavior of window.open differently with regard to users' browser preferences. 您不能指望 window.open 在所有Internet Explorer,Firefox和Chrome中都有相同的行为,因为它们处理用户浏览器首选项的方式不同 .

    补充阅读

  • -6

    如果您使用 window.open(url, '_blank') ,它将在Chrome上被阻止(弹出窗口拦截器) .

    试试这个:

    $('#myButton').click(function () {
        var redirectWindow = window.open('http://google.com', '_blank');
        redirectWindow.location;
    });
    
  • 15

    一个班轮:

    Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();
    

    要么

    随着 jQuery 我正在使用这个:

    var url = "http://google.com";
    $("<a>").attr("href", url).attr("target", "_blank")[0].click();
    

    它创建一个虚拟 a 元素,给它 target="_blank" 所以它在新标签中打开,给它正确 url href 然后点击它 .

    如果你愿意,基于此你可以创建一些功能:

    function openInNewTab(url) {
        $("<a>").attr("href", url).attr("target", "_blank")[0].click();
    }
    

    然后你可以使用它像:

    openInNewTab("http://google.com");
    

    对于 non-jQuery 场景,该函数将如下所示:

    function openInNewTab(url) {
        var a = document.createElement("a");
        a.target = "_blank";
        a.href = url;
        a.click();
    }
    
    // And then
    openInNewTab("http://google.com");
    
  • 10

    这是一招,

    function openInNewTab(url) {
      var win = window.open(url, '_blank');
      win.focus();
    }
    

    在大多数情况下,这应该直接发生在链接的 onclick 处理程序中,以防止弹出窗口阻止程序和默认的"new window"行为 . 您可以这样做,或者通过向 DOM 对象添加事件侦听器 .

    <div onclick="openInNewTab('www.test.com');">Something To Click On</div>
    

    http://www.tutsplanet.com/open-url-new-tab-using-javascript-196/

  • 11

    或者您可以创建一个链接元素并单击它...

    var evLink = document.createElement('a');
    evLink.href = 'http://' + strUrl;
    evLink.target = '_blank';
    document.body.appendChild(evLink);
    evLink.click();
    // Now delete it
    evLink.parentNode.removeChild(evLink);
    

    任何弹出窗口拦截器都不应该阻止它......希望如此 .

  • 165

    您可以使用 form 的技巧:

    $(function () {
        $('#btn').click(function () {
            openNewTab("http://stackoverflow.com")
            return false;
        });
    });
    
    function openNewTab(link) {
        var frm = $('<form   method="get" action="' + link + '" target="_blank"></form>')
        $("body").append(frm);
        frm.submit().remove();
    }
    

    jsFiddle demo

  • -4

    这可能是一个黑客,但在Firefox中,如果你指定第三个参数'fullscreen = yes',它会打开一个全新的窗口 .

    例如,

    <a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>
    

    它似乎实际上覆盖了浏览器设置 .

  • -10

    我将与编写的人(在此解释)稍微同意:“对于现有网页中的链接,如果新页面是同一网站的一部分,浏览器将始终在新选项卡中打开链接现有的网页 . “对我来说,至少,这个“一般规则”适用于Chrome,Firefox,Opera,IE,Safari,SeaMonkey和Konqueror .

    无论如何,有一种不那么复杂的方式来利用对方提出的内容 . 假设我们正在讨论您自己的网站(下面的“thissite.com”),您想控制浏览器的功能,那么,在下面,您希望“specialpage.htm”为EMPTY,不完全是HTML(节省了从服务器发送数据的时间!) .

    var wnd, URL;  //global variables
    
     //specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
     wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); //get reference to just-opened page
     //if the "general rule" above is true, a new tab should have been opened.
     URL = "http://www.someothersite.com/desiredpage.htm";  //ultimate destination
     setTimeout(gotoURL(),200);  //wait 1/5 of a second; give browser time to create tab/window for empty page
    
    
     function gotoURL()
     { wnd.open(URL, "_self");  //replace the blank page, in the tab, with the desired page
       wnd.focus();             //when browser not set to automatically show newly-opened page, this MAY work
     }
    
  • 0

    作者无法做任何事情可以选择在新选项卡中打开而不是在新窗口中打开 . 这是用户偏好 .

    CSS3提出target-new,但the specification was abandoned .

    reverse 不是真的;通过在 window.open 的第三个参数中指定窗口的尺寸,可以在首选项用于选项卡时触发新窗口 .

  • 1339

    这个问题有一个答案,但事实并非如此 .

    我找到了一个简单的解决方法:

    第1步:创建一个不可见的链接:

    <a id="yourId" href="yourlink.html" target="_blank" style="display: none;"></a>

    第2步:以编程方式单击该链接:

    document.getElementById("yourId").click();

    干得好!为我的魅力 .

  • 328

    一个有趣的事实是,如果用户未调用操作(单击按钮或某物)或者它是异步的,则无法打开新选项卡,例如,这不会在新选项卡中打开:

    $.ajax({
        url: "url",
        type: "POST",
        success: function() {
            window.open('url', '_blank');              
        }
    });
    

    但这可能会在新选项卡中打开,具体取决于浏览器设置:

    $.ajax({
        url: "url",
        type: "POST",
        async: false,
        success: function() {
            window.open('url', '_blank');              
        }
    });
    
  • 228

    从Firefox(Mozilla)扩展中打开一个新选项卡如下所示:

    gBrowser.selectedTab = gBrowser.addTab("http://example.com");
    
  • 56

    如果您只是想加载到元素上,请尝试使用它 . 在页面加载时,它将使用正确的属性添加您的目标属性 .

    $(your_element_here).prop('target','_ blank');

  • 54

    如果链接位于同一域(在同一网站上),浏览器将始终在新选项卡中打开链接 . 如果该链接位于其他某个域上,则会在新的选项卡/窗口中打开它,具体取决于浏览器设置 .

    所以,根据这个,我们可以使用:

    <a class="my-link" href="http://www.mywebsite.com" rel="http://www.otherwebsite.com">new tab</a>
    

    并添加一些jQuery代码:

    jQuery(document).ready(function () {
        jQuery(".my-link").on("click",function(){
            var w = window.open('http://www.mywebsite.com','_blank');
            w.focus();
            w.location.href = jQuery(this).attr('rel');
            return false;
        });
    });
    

    因此,首先使用_blank目标在同一网站上打开新窗口(它将在新选项卡中打开它),然后在新窗口中打开所需的网站 .

  • 33

    如果您只想打开外部链接(转到其他站点的链接),那么这个JavaScript / jQuery的效果很好:

    $(function(){
        var hostname = window.location.hostname.replace('www.', '');
        $('a').each(function(){
            var link_host = $(this).attr('hostname').replace('www.', '');
            if (link_host !== hostname) {
                $(this).attr('target', '_blank');
            }
        });
    });
    
  • 18
    (function(a){
    document.body.appendChild(a);
    a.setAttribute('href', location.href);
    a.dispatchEvent((function(e){
        e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
        return e
    }(document.createEvent('MouseEvents'))))}(document.createElement('a')))
    
  • 13

    我认为你无法控制这一点 . 如果用户已将浏览器设置为在新窗口中打开链接,则无法强制此操作在新选项卡中打开链接 .

    JavaScript open in a new window, not tab

  • 11

    省略[strWindowFeatures]参数将打开一个新选项卡,除非浏览器设置覆盖(浏览器设置胜过JavaScript) .

    新窗口

    var myWin = window.open(strUrl, strWindowName, [strWindowFeatures]);
    

    新标签

    var myWin = window.open(strUrl, strWindowName);
    
    • 要么 -
    var myWin = window.open(strUrl);
    
  • 0

    为了详细说明斯蒂芬斯皮尔伯格的答案,我在这种情况下这样做了:

    $('a').click(function() {
      $(this).attr('target', '_blank');
    });
    

    这样,就在浏览器将跟随我设置目标属性的链接之前,所以它将在新的选项卡或窗口( depends on user's settings )中打开链接 .

  • -1

    如果在实际点击事件中没有发生 window.open() ,则不会在新标签中打开 . 在给定的示例中,URL正在实际的单击事件上打开 . This will work provided the user has appropriate settings in the browser .

    <a class="link">Link</a>
    <script  type="text/javascript">
         $("a.link").on("click",function(){
             window.open('www.yourdomain.com','_blank');
         });
    </script>
    

    同样,如果您尝试在click函数中执行Ajax调用并希望在成功时打开一个窗口,请确保使用 async : false 选项集进行Ajax调用 .

  • -3

    这种方式类似于上述解决方案,但实现方式不同

    .social_icon - >一些带CSS的类

    <div class="social_icon" id="SOME_ID" data-url="SOME_URL"></div>
    
    
     $('.social_icon').click(function(){
    
            var url = $(this).attr('data-url');
            var win = window.open(url, '_blank');  ///similar to above solution
            win.focus();
       });
    
  • -10

    This has nothing to do with browser settings 如果您尝试从自定义功能打开新选项卡 .

    在此页面中,打开JavaScript控制台并键入:

    document.getElementById("nav-questions").setAttribute("target", "_blank");
    document.getElementById("nav-questions").click();
    

    并且无论您的设置如何,它都会尝试打开弹出窗口,因为“点击”来自自定义操作 .

    为了在链接上表现得像一个真实的'mouse click',你需要按照@spirinvladimir's advice并真正创建它:

    document.getElementById("nav-questions").setAttribute("target", "_blank");
    document.getElementById("nav-questions").dispatchEvent((function(e){
      e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                        false, false, false, false, 0, null);
      return e
    }(document.createEvent('MouseEvents'))));
    

    这是一个完整的例子(不要在jsFiddle或类似的在线编辑器上尝试它,因为它不会让你从那里重定向到外部页面):

    <!DOCTYPE html>
    <html>
    <head>
      <style>
        #firing_div {
          margin-top: 15px;
          width: 250px;
          border: 1px solid blue;
          text-align: center;
        }
      </style>
    </head>
    <body>
      <a id="my_link" href="http://www.google.com"> Go to Google </a>
      <div id="firing_div"> Click me to trigger custom click </div>
    </body>
    <script>
      function fire_custom_click() {
        alert("firing click!");
        document.getElementById("my_link").dispatchEvent((function(e){
          e.initMouseEvent("click", true, true, window, /* type, canBubble, cancelable, view */
                0, 0, 0, 0, 0,              /* detail, screenX, screenY, clientX, clientY */
                false, false, false, false, /* ctrlKey, altKey, shiftKey, metaKey */
                0, null);                   /* button, relatedTarget */
          return e
        }(document.createEvent('MouseEvents'))));
      }
      document.getElementById("firing_div").onclick = fire_custom_click;
    </script>
    </html>
    
  • 1

    如何用 _blank 作为 target 属性值创建一个 <a> ,将 url 创建为 href ,样式显示:隐藏一个子元素?然后添加到DOM,然后在children元素上触发click事件 .

    更新

    这不起作用 . 浏览器会阻止默认行为 . 它可以通过编程方式触发,但不遵循默认行为 .

    检查并亲眼看看:http://jsfiddle.net/4S4ET/

  • 2

    为页面上的所有超链接和表单指定默认目标(非JavaScript):

    <head>
      <base target="_blank">
    </head>
    

相关问题