1

How can i redirect users of my website to another URL in a new tab, without switching to the new tab? I know this question has been asked so much time but all the solutions dont work for me, i found this code on stackoverflow:

function openWindow( url )
{
window.open(url, '_blank');

window.focus();
}

<a href="https://www.bing.com/search?q=2146217" onclick="javascript:openWindow(this.href);return false;">Click Me</a>

but it does not work... does anyone have a solution for me? thanks!

  • 1
    Does this answer your question? [How to open new tab in JavaScript without switching to the new tab?](https://stackoverflow.com/questions/7924232/how-to-open-new-tab-in-javascript-without-switching-to-the-new-tab) – CootMoon Feb 05 '23 at 18:01
  • 1
    no, that's actually the question i got the code from that did not work :) – denoryprogrammer Feb 05 '23 at 18:17
  • According to the answers in that question, it doesn't work on most browsers. Because the question was also asked a long time ago, I bet that it won't work on any modern browser. My assumption is that in new browsers this is completely disabled as to stop bad actors from switching tabs without the users permission. – CootMoon Feb 05 '23 at 18:25

2 Answers2

1

Other than window.focus(), there isn't really a way to do that. On some devices, you can click using the scroll wheel or right-click the link/button to open something without opening a new tab. That's probably your best bet.

OhNoItsA8
  • 58
  • 5
0

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

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

It is very browser specific if you can use window.focus() to call back to the tab. My assumption is that in new browsers, this is completely disabled as to stop bad actors from switching tabs without the users permission.

CootMoon
  • 522
  • 4
  • 22