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!
CodePudding user response:
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.
CodePudding user response:
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.