3

When opening a window using JavaScript, it's possible to capture a reference to the opened window/tab, that can then be used to see if the window/tab has been closed again for example. Something like this (somewhat contrived example):

var foo = window.open( 'http://www.foo.bar' );
...
if ( !foo || foo.closed ) {
    ...

But is it possible to achieve something similar using anchor elements? For example, if I have the link

<a href="http://www.foo.bar" target="_blank">Foo</a>

on my website, is there any way to attach an event listener and obtain a reference to whatever window/tab is opened when this anchor element is triggered, and then use this in JavaScript? Listening to the click event could work, but are there other ways that cover it better? (For example, you can tab to an anchor element and press enter to open it too, which won't register as a click event)

Martin Wedvich
  • 2,158
  • 2
  • 21
  • 37
  • 1
    this might help http://stackoverflow.com/questions/8927208/catching-event-when-following-a-link – pax162 Oct 23 '13 at 14:27
  • Good question; I have no idea but look forward to see the answer! – Marcus Stade Oct 23 '13 at 14:28
  • if both windows are in the same domain you might be able to avoid putting any code on the anchor tag all together by having the child window pass its window object to the parent when it opens. – jbabey Oct 23 '13 at 16:42

1 Answers1

1

Pressing enter while focused on an anchor tag will fire the click event handler in modern browsers. I tested this in Chrome 30.

Proof: http://jsfiddle.net/HZvPT/

So your click handler would grab the href attribute, call window.open (storing the return value of the window), and then e.preventDefault() to stop the anchor tag from performing its default behavior (which would be opening a second window, not good).

jbabey
  • 45,965
  • 12
  • 71
  • 94
  • 1
    But as far as I know this won't work for contextual menus, where you get the option to open in a new tab etc. Unfortunately, from what I can tell there doesn't seem to be a catch-all "activate" event or such that browsers should dispatch when activating a link. – Marcus Stade Oct 23 '13 at 14:59
  • @macke true, i am not sure if there is any way to interact with those right click menus. – jbabey Oct 23 '13 at 16:41
  • Yeah, I doubt that there's any way to currently do what the OP is asking for to be honest. Would love to know if there is! – Marcus Stade Oct 23 '13 at 17:23