繁体   English   中英

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

[英]Open a URL in a new tab (and not a new window)

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

我看过相关的问题,其中的回复类似于:

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

但是它们都不适合我,浏览器仍然试图打开一个弹出窗口 window。

这是套路

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

//or just
window.open(url, '_blank').focus();

在大多数情况下,这应该直接在链接的onclick处理程序中发生,以防止弹出窗口阻止程序和默认的“新窗口”行为。 您可以通过这种方式或通过向DOM对象添加事件侦听器来实现。

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

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

作者无法选择在新选项卡中打开而不是在新窗口中打开; 这是用户偏好 (请注意,大多数浏览器中的默认用户首选项是针对新选项卡的,因此在未更改该首选项的浏览器上进行的简单测试不会证明这一点。)

CSS3 提出了target-new ,但该规范被放弃了

反之则不然 通过在window.open()的第三个参数中为窗口指定某些窗口功能,您可以在首选选项卡时触发一个新窗口。

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 调用并希望在成功时打开一个窗口,请确保您在执行 Ajax 调用时设置了async : false选项。

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

它创建一个虚拟的 a 元素,给它 target="_blank" 以便它在新选项卡中打开,给它适当的 url href 然后单击它。

然后你可以像这样使用它:

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

重要的提示:

openInNewTab (以及此页面上的任何其他解决方案)必须在所谓的“可信事件”回调期间调用 - 例如。 单击事件期间(不需要直接在回调函数中,但在单击动作期间)。 否则打开新页面会被浏览器拦截

如果您在某个随机时刻(例如,在某个时间间隔内或在服务器响应之后)手动调用它 - 它可能会被浏览器阻止(这是有道理的,因为这会带来安全风险并可能导致糟糕的用户体验)

window.open无法在所有浏览器的新标签页中可靠地打开弹出窗口

不同的浏览器以不同的方式实现window.open的行为,尤其是在用户的浏览器偏好方面。 您不能期望window.open的相同行为在所有 Internet Explorer、Firefox 和 Chrome 中都成立,因为它们处理用户浏览器首选项的方式不同。

例如,Internet Explorer (11) 用户可以选择在新窗口或新选项卡中打开弹出窗口,您不能强制 Internet Explorer 11 用户通过window.open以某种方式打开弹出窗口,正如Quentin 的回答中所暗示的那样

对于 Firefox (29) 用户,使用window.open(url, '_blank')取决于他们浏览器的选项卡首选项,尽管您仍然可以通过指定宽度和高度来强制他们在新窗口中打开弹出窗口(请参阅“What About Chrome?”部分)。

示范

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

浏览器 (11)

Internet Explorer 设置对话框 1

Internet Explorer 选项卡设置对话框

测试页

设置 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>

观察弹出窗口是在新窗口中打开的,而不是在新选项卡中打开

您还可以在 Firefox (29) 中测试这些片段,并将其选项卡首选项设置为新窗口,并查看相同的结果。

铬呢? 它实现window.open与 Internet Explorer (11) 和 Firefox (29) 不同。

我不是 100% 确定,但看起来 Chrome(版本34.0.1847.131 m )似乎没有任何设置,用户可以使用它来选择是否在新窗口或新选项卡中打开弹出窗口(例如Firefox 和 Internet Explorer 都有)。 我检查了 Chrome 文档管理弹出窗口,但它没有提到任何关于这类事情的内容。

此外,再一次,不同的浏览器似乎以不同的方式实现window.open的行为 在 Chrome 和 Firefox 中,指定宽度和高度将强制弹出窗口,即使用户已将 Firefox (29) 设置为在新选项卡中打开新窗口(如JavaScript 在新窗口中打开的答案中所述,而不是选项卡) :

<!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>

但是,如果用户将选项卡设置为他们的浏览器首选项,上面的相同代码片段将始终在 Internet Explorer 11 中打开一个新选项卡,即使不指定宽度和高度也会强制为他们弹出新窗口。

因此,Chrome 中window.open的行为似乎是在onclick事件中使用时在新选项卡中打开弹出窗口,在从浏览器控制台使用时在新窗口中打开它们( 如其他人所述),并打开它们在指定宽度和高度的新窗口中。

概括

不同的浏览器根据用户的浏览器首选项实现window.open的行为不同。 您不能期望window.open的相同行为在所有 Internet Explorer、Firefox 和 Chrome 中都成立,因为它们处理用户浏览器首选项的方式不同。

补充阅读

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

尝试这个:

//With JQuery

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

使用纯 JavaScript,

document.querySelector('#myButton').onclick = function() {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
};

我使用以下方法,效果很好!

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

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

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

这样,就在浏览器跟随链接之前,我正在设置目标属性,因此它将在新选项卡或窗口中打开链接(取决于用户的设置)。

jQuery 中的一行示例:

$('a').attr('target', '_blank').get(0).click();
// The `.get(0)` must be there to return the actual DOM element.
// Doing `.click()` on the jQuery object for it did not work.

这也可以仅使用本机浏览器 DOM API 来完成:

document.querySelector('a').setAttribute('target', '_blank');
document.querySelector('a').click();

我认为你无法控制这一点。 如果用户已将其浏览器设置为在新窗口中打开链接,则您不能强制这样做在新选项卡中打开链接。

JavaScript 在新窗口中打开,而不是选项卡

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

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

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

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

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

新窗户

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

新标签

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

- 或者 -

var myWin = window.open(strUrl);
function openTab(url) {
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  link.remove();
}
(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')))

如果您尝试从自定义功能打开新选项卡,则这与浏览器设置无关

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

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

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

为了表现得像链接上的实际“鼠标点击”,您需要遵循@spirinvladimir 的建议真正创建它:

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>

您可以使用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 演示

是否在新标签页或新窗口中打开 URL,实际上是由用户的浏览器首选项控制的。 在 JavaScript 中无法覆盖它。

window.open()行为取决于它的使用方式。 如果它是作为用户操作的直接结果调用的,例如单击按钮,它应该可以正常工作并打开一个新选项卡(或窗口):

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {
    // open a new tab
    const tab = window.open('https://attacomsian.com', '_blank');
});

但是,如果您尝试从 AJAX 请求回调打开一个新选项卡,浏览器将阻止它,因为它不是直接的用户操作。

绕过弹出窗口阻止程序并从回调中打开一个新选项卡,这里有一个小技巧

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {

    // open an empty window
    const tab = window.open('about:blank');

    // make an API call
    fetch('/api/validate')
        .then(res => res.json())
        .then(json => {

            // TODO: do something with JSON response

            // update the actual URL
            tab.location = 'https://attacomsian.com';
            tab.focus();
        })
        .catch(err => {
            // close the empty window
            tab.close();
        });
});

查询

$('<a />',{'href': url, 'target': '_blank'}).get(0).click();

JS

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

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

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);

这不应该被任何弹出窗口阻止程序阻止...希望如此。

这个问题有答案,也不是没有。

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

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

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

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

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

干得好! 对我很有魅力。

不要使用 target="_blank"

在我的情况下,始终为该窗口使用特定名称meaningfulName ,在这种情况下,您可以节省处理器资源:

button.addEventListener('click', () => {
    window.open('https://google.com', 'meaningfulName')
})

这样,当您单击按钮 10 次时,浏览器将始终在一个新选项卡中重新呈现它,而不是在 10 个不同的选项卡中打开它,这会消耗更多资源。

您可以在MDN上阅读有关此内容的更多信息。

在此处输入图片说明

我研究了很多关于如何打开新标签并保持在同一个标​​签上的信息。 我找到了一个小技巧来做到这一点。 假设您有需要打开的 url - newUrl和旧 url - currentUrl ,您需要在打开新选项卡后保留它们。 JS 代码如下所示:

// init urls
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
// open window with url of current page, you will be automatically moved 
// by browser to a new opened tab. It will look like your page is reloaded
// and you will stay on same page but with new page opened
window.open(currentUrl , '_blank');
// on your current tab will be opened new url
location.href = newUrl;

如何使用_blank作为target属性值和url作为href创建一个<a> ,样式 display:hidden with aa children ? 然后添加到 DOM,然后在子元素上触发 click 事件。

更新

那行不通。 浏览器会阻止默认行为。 它可以以编程方式触发,但它不遵循默认行为。

自己检查一下: http : //jsfiddle.net/4S4ET/

这可能是一个 hack,但在 Firefox 中,如果您指定第三个参数 'fullscreen=yes',它会打开一个新窗口。

例如,

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

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

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

$ {your_element_here).prop('target','_blank');

window.open(url)将在新的浏览器选项卡中打开 url。 下面的 JS 替代它

let a= document.createElement('a');
a.target= '_blank';
a.href= 'https://support.wwf.org.uk/';
a.click(); // we don't need to remove 'a' from DOM because we not add it

这是工作示例(stackoverflow 片段不允许打开新选项卡)

这是我们如何将其放入 HTML 标签中的示例

<button onClick="window.open('https://stackoverflow.com/','_blank')">Stackoverflow</button>

从 Firefox (Mozilla) 扩展程序中打开一个新选项卡是这样的:

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

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

.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();
   });

这对我有用,只需阻止该事件,将 url 添加到<a> tag然后在该tag上触发点击事件。

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>

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

如果你建议足够多的“类似标签的东西”,可能会得到一个标签, 根据 Nico 对这个更具体的 chrome 问题的回答

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

免责声明:这不是万能药。 这仍然取决于用户和浏览器。 现在至少您已经为您希望窗口的外观指定了另一种偏好。

我将有点同意写(在此处解释)的人的观点:“对于现有网页中的链接,如果新网页与现有的网页。” 至少对我来说,这个“一般规则”适用于 Chrome、Firefox、Opera、IE、Safari、SeaMonkey 和 Konqueror。

无论如何,有一种不太复杂的方法可以利用其他人提供的内容。 假设我们正在谈论您自己的网站(下面的“thissite.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
 }

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

网站可以以某种方式做到这一点。 (我没有时间从这个混乱中提取它,但这是代码)

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)

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

因此,根据此,我们可以使用:

<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目标在同一网站上打开新窗口(它将在新标签页中打开),然后在该新窗口中打开所需的网站。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM