How to open new tab in JavaScript without switching to the new tab?

前端 未结 8 1018
时光取名叫无心
时光取名叫无心 2020-11-29 04:11

How can I open a new tab using javascript without switching to the new tab?
For example, when a user clicks on a link a new tab is to be opened, but the user should stay

相关标签:
8条回答
  • 2020-11-29 04:46

    Unfortunately, you can't currently do that -- but you can get close. You can open a new window, and if you do that without specifying any window dimensions or window features, most modern browsers will open a new tab instead (depending on the user's preferences, but then, you want to do what the user prefers anyway, right?). So just window.open(url) or window.open(url, name) if you're going to use the name for something. Be sure to do this in direct response to a user-initiated event, otherwise the browser's pop-up blocker will probably...block the pop-up. :-)

    Live example

    Regarding keeping focus on your window...good luck with that. You can call window.focus() after window.open(...), but in my experience it doesn't usually work.

    Throwing it out there: If you make the thing the user interacts with a genuine link with a URL, the user can decide whether to open it in a new tab, a new window, whatever and whether to give it focus (if they're sophisticated enough to know Shift+Click and Ctrl+Shift+Click, or the right-click menu).

    0 讨论(0)
  • 2020-11-29 04:49

    The web browser automatically focuses on the new tab, but you can call the focus back:

    function openWindow( url )
    {
      window.open(url, '_blank');
      window.focus();
    }
    
    <a href="http://www.example.com/" onclick="javascript:openWindow(this.href);return false;">Click Me</a>
    
    0 讨论(0)
提交回复
热议问题