Reputation: 1186
Can we get a reference to a tab which was opened by setting target
attribute of anchor element to _blank
.
I basically create a new hidden link and append it to a DOM and then I programmatically simulate click event on that element, is there a way to get a reference to a newly opened tab like we can with window.open
by doing:
var newTab = window.open('http://www.google.com/');
EDIT: Before marking question as duplicate note that I'm unable to use window.open
at all, hence this question.
Upvotes: 1
Views: 1918
Reputation: 844
If you can't use code directly inside the anchor, you could try to get the reference afterwards (doesn't work in IE).
However you need to set a different target than _blank
, it will still open a new tab though.
1) Define a target name for your anchor
<a href="https://google.com" target="myTarget">Click me</a>
2) Get the reference with this "hack":
var ref = window.open('', 'myTarget');
For more information, see https://medium.com/@bluepnume/every-known-way-to-get-references-to-windows-in-javascript-223778bede2d
Upvotes: 2
Reputation: 144
There are a few red flags worth considering for the functionality you seek to build before you proceed:
You do not have much control (as a developer) to force new links to be opened in browser tabs. That's based on the user's preference as per this answer
window.open
docs indicates it returns a null
value "If the window couldn't be opened". You can use this to loosely check whether a new window was opened or not. However, this might not be consistent across the different browsers.
I will suggest you look at other options (if any) before going down this path.
All the best :)
Upvotes: 0