0

Is it possible in Javascript to open up a new tab, and then listen for that tab firing an event?

I've seen this for listening to certain tab events, but can instead of window, I target the specific tab I opened?

Community
  • 1
  • 1
TMH
  • 6,096
  • 7
  • 51
  • 88

3 Answers3

1

No you can't. Well, not directly.

For obvious security reasons javascript can only access data from it's own tab/window. You can however use cookies, locastorage or ... to store and read data from the same domain.

You could add an EventListner to the localstorage object (that is shared between domains). Soundcloud for instance does this.

Edit: I think there is a confusion between window.open and a new tab.

window.open opens a pop up. You can then access that popup from within your script. Note however that behaviour of how pop-ups are shown vary from browser to browser. Some open it in a new tab, some in a new window, ... Note however that to be able to access the popup, it has to be same domain, protocol, port, ...

this however doesn't work if the user manually opens a new window/tab to your site because you don't have a reference to it.

Community
  • 1
  • 1
Pinoniq
  • 1,365
  • 9
  • 13
  • Ahh okay, could this be done using `window.open` directly in Javascript? Or does the rule still apply then? – TMH Jul 11 '14 at 12:57
  • has nothing to do with it... Read my answer again ;) If both tabs/windows are on the same domain (e.g. soundcloud.com/a and soundcloud.com/b) it doens't matter how you open them. they will be aple to access the same localstorage object (and also cookies, ...) – Pinoniq Jul 11 '14 at 13:55
1

The following solution worked for me:

Parent Window

 var win = window;
 win.open('url', 'newWindow', 'height=300,width=300');

 win.addEventListener('message', function(response){
    console.log(response.data);
},false);

Child Window

window.opener.postMessage('Success', "*");
0

This seems to work nicely for me

In the parent window

var form = window.open('/formsv2/add', '_blank', 'resizable=1', true);
form.addEventListener('formAdded', function(data) {
    console.log('formAddedEvent');
    console.log(data.name);
    console.log(data.id);
    $('#formIdSelect').append('<option value="'+data.id+'">'+data.name+'</option>').val(data.id);
});

In the popup window

var evt = document.createEvent("Events")
evt.initEvent('formAdded', true, true); //true for can bubble, true for cancelable
evt.name = $('#title').val();
evt.id = data.form;
document.dispatchEvent(evt);
RevanProdigalKnight
  • 1,316
  • 1
  • 14
  • 23
TMH
  • 6,096
  • 7
  • 51
  • 88