我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。

我见过一些相关的问题,其中的回答大致如下:

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

但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。


当前回答

我将在一定程度上同意下面的人的观点(此处转述):“对于现有网页中的链接,如果新网页与现有网页是同一网站的一部分,浏览器将始终在新选项卡中打开链接。”至少对我来说,这条“通用规则”适用于Chrome、Firefox、Opera、Internet Explorer、Safari、SeaMonkey和Konqueror。

不管怎样,有一种不那么复杂的方法可以利用对方所呈现的内容。假设我们讨论的是您自己的网站(下面的“thisite.com”),您希望在其中控制浏览器的功能,那么,下面,您希望“specialpage.htm”为空,其中完全没有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
 }

其他回答

有很多答案副本建议使用“_blank”作为目标,但我发现这并不奏效。正如Prakash指出的,这取决于浏览器。但是,您可以向浏览器提出某些建议,例如窗口是否应具有位置栏。

如果你提出了足够多的“类似标签的东西”,你可能会得到一个标签,正如Nico对铬的这个更具体问题的回答:

window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');

免责声明:这不是万能药。这仍然取决于用户和浏览器。现在,至少您为希望窗口的外观指定了一个首选项。

不知怎么的,一个网站可以做到这一点

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)

这对我有效。只需阻止事件,将URL添加到<a>标记,然后在该标记上触发单击事件。

JavaScript

$('.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>

window.open()不会在新选项卡中打开,如果它不是在实际的单击事件中发生的。在给定的示例中,URL是在实际单击事件上打开的。如果用户在浏览器中有适当的设置,这将起作用。

<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调用。

只要省略strWindowFeatures参数,就会打开一个新选项卡,除非浏览器设置覆盖它(浏览器设置胜过JavaScript)。

新建窗口

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

新建选项卡

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

--或--

var myWin = window.open(strUrl);