1

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.

whatamidoingwithmylife
  • 1,119
  • 1
  • 16
  • 35

2 Answers2

1

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

Stefan Blamberg
  • 816
  • 9
  • 24
  • That's what I was looking for, even though I did mention we I can't use window.open() so basically it's a loop, but nevertheless this does answer my original question on how to get a reference to a tab opened by element. – whatamidoingwithmylife Sep 14 '18 at 13:30
0

There are a few red flags worth considering for the functionality you seek to build before you proceed:

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

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