在新标签页中打开URL(而不是新窗口)

2813

我正在尝试在新标签页中打开一个URL,而不是弹出窗口。

我看到了类似的问题,其响应大致如下:

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

但是这些方法都没有对我起作用,浏览器仍然试图打开一个弹出窗口。


96
通常这是个人偏好的问题。有些人喜欢用窗口(并强烈坚持这种行为),有些人喜欢用标签页(也同样强烈坚持)。因此,你要改变的是一种通常被认为是品味问题而非设计问题的行为方式。 - Jared Farrish
56
JavaScript 不了解您的浏览器、选项卡和窗口之间的区别,所以打开新窗口的方式完全由浏览器决定。 - Andrey
8
我该如何配置Chrome在新标签页中显示页面,而不是弹出窗口? - Mark
13
在Chrome中,Gmail可以通过某种方式实现此功能。按住Shift并单击电子邮件行即可在新窗口中打开该邮件。按住Ctrl并单击则将其在新标签页中打开。唯一的问题是:深入挖掘Gmail的代码可能非常麻烦。 - Sergio
58
@Sergio,这是任何链接的默认浏览器行为(至少适用于 Chrome 和 Firefox),与 Gmail 无关。 - Qtax
显示剩余13条评论
33个回答

-9
如果您只想打开外部链接(指链接到其他网站的链接),那么这段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');
        }
    });
});

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Nuri Akman

-10

不知何故一个网站可以做到这一点。(我没有时间从这个混乱中提取它,但这是代码。)

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)

7
请在直接放置代码之前添加上下文信息。 - chntgomez

-10

如果链接在同一域名下(同一网站),浏览器将始终在新标签页中打开链接。如果链接在其他域名下,则根据浏览器设置在新标签页/窗口中打开。

因此,根据这个规则,我们可以使用:

<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目标打开新窗口(它将在新标签页中打开),然后在该新窗口中打开您想要的网站。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接