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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4907843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:41:25  来源:igfitidea点击:

Open a URL in a new tab (and not a new window)

javascript

提问by Mark

I'm trying to open a URLin a new tab, as opposed to a popup window.

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

I've seen related questions where the responses would look something like:

我看过相关的问题,其中的回复看起来像:

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

But none of them worked for me, the browser still tried to open a popup window.

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

采纳答案by Quentin

Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.)

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

CSS3 proposed target-new, but the specification was abandoned.

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

The reverseis not true; by specifying dimensions for the window in the third argument of window.open(), you can trigger a new window when the preference is for tabs.

反向是不正确的; 通过在 的第三个参数中指定窗口的尺寸window.open(),您可以在首选选项卡时触发一个新窗口。

回答by Rinto George

This is a trick,

这是套路

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

In most cases, this should happen directly in the onclickhandler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOMobject.

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

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

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

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

回答by Venkat Kotra

window.open()will not open in a new tab if it is not happening on the actual click event. In the example given the URL is being opened on the actual click event. This will work provided the user has appropriate settings in the browser.

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

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

Similarly, if you are trying to do an Ajax call within the click function and want to open a window on success, ensure you are doing the Ajax call with the async : falseoption set.

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

回答by Venkat Kotra

window.openCannot Reliably Open Popups in a New Tab in All Browsers

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

Different browsers implement the behavior ofwindow.openin different ways, especially with regard to a user's browser preferences.You cannot expect the same behavior for window.opento be true across all of Internet Explorer, Firefox, and Chrome, because of the different ways in which they handle a user's browser preferences.

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

For example, Internet Explorer (11) users can choose to open popups in a new window or a new tab, you cannot force Internet Explorer 11 users to open popups in a certain way throughwindow.open, as alluded to in Quentin's answer.

例如,Internet Explorer (11) 用户可以选择在新窗口或新选项卡中打开弹出窗口,您不能window.openQuentin 的回答中提到的那样强制 Internet Explorer 11 用户以某种方式打开弹出窗口

As for Firefox (29) users, using window.open(url, '_blank')depends on their browser's tab preferences,though you can still force them to open popups in a new window by specifying a width and height (see "What About Chrome?" section below).

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

Demonstration

示范

Go to your browser's settings and configure it to open popups in a new window.

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

Internet Explorer (11)

浏览器 (11)

Internet Explorer settings dialog 1

Internet Explorer 设置对话框 1

Internet Explorer tab settings dialog

Internet Explorer tab settings dialog

Test Page

测试页

After setting up Internet Explorer (11) to open popups in a new window as demonstrated above, use the following test page to test window.open:

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

Observe that the popups are opened in a new window, not a new tab.

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

You can also test those snippets above in Firefox (29) with its tab preference set to new windows, and see the same results.

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

What About Chrome? It Implements window.openDifferently from Internet Explorer (11) and Firefox (29).

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

I'm not 100% sure, but it looks like Chrome (version 34.0.1847.131 m) does not appear to have any settings that the user can use to choose whether or not to open popups in a new window or a new tab (like Firefox and Internet Explorer have). I checked the Chrome documentation for managing pop-ups, but it didn't mention anything about that sort of thing.

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

Also, once again, different browsers seem to implement the behavior ofwindow.opendifferently.In Chrome and Firefox, specifying a width and height will force a popup,even when a user has set Firefox (29) to open new windows in a new tab (as mentioned in the answers to JavaScript open in a new window, not tab):

此外,再一次,不同的浏览器似乎实现了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>

However, the same code snippet above will always open a new tab in Internet Explorer 11 if users set tabs as their browser preferences,not even specifying a width and height will force a new window popup for them.

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

So the behavior of window.openin Chrome seems to be to open popups in a new tab when used in an onclickevent, to open them in new windows when used from the browser console (as noted by other people), and to open them in new windows when specified with a width and a height.

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

Summary

概括

Different browsers implement the behavior ofwindow.opendifferently with regard to users' browser preferences.You cannot expect the same behavior for window.opento be true across all of Internet Explorer, Firefox, and Chrome, because of the different ways in which they handle a user's browser preferences.

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

Additional Reading

补充阅读

回答by pie6k

One liner:

一个班轮:

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

It creates a virtual aelement, gives it target="_blank"so it opens in a new tab, gives it proper urlhrefand then clicks it.

它创建一个虚拟a元素,给它target="_blank"一个新选项卡,给它适当的urlhref然后单击它。

And if you want, based on that you can create some function:

如果你愿意,你可以在此基础上创建一些函数:

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

and then you can use it like:

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

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

Important note:

重要的提示:

openInNewTab(as well as any other solution on this page) must be called during user action callback - eg. inside click event (not necessary in callback function directly, but during click action).

openInNewTab(以及此页面上的任何其他解决方案)必须在用户操作回调期间调用 - 例如。内部单击事件(不需要直接在回调函数中,但在单击操作期间)。

If you'll call it manually in some random moment (eg. inside an interval or after server response) - it might be blocked by the browser (which makes sense as it'd be a security risk and might lead to very poor user experience)

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

回答by Mohammed Safeer

If you use window.open(url, '_blank'), it will be blocked (popup blocker) on Chrome.

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

Try this:

尝试这个:

//With JQuery

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

With pure JavaScript,

使用纯 JavaScript,

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

回答by arikfr

To elaborate Steven Spielberg's answer, I did this in such a case:

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

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

This way, just before the browser will follow the link I'm setting the target attribute, so it will make the link open in a new tab or window (depends on user's settings).

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

One line example in jQuery:

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.

This can also be accomplished just using native browser DOM APIs as well:

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

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

回答by Ezequiel García

I use the following and it works very well!

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

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

回答by karaxuna

An interesting fact is that the new tab can not be opened if the action is not invoked by the user (clicking a button or something) or if it is asynchronous, for example, this will NOT open in new tab:

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

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

But this may open in a new tab, depending on browser settings:

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

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

回答by Fran Verona

I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.

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

JavaScript open in a new window, not tab

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