Dave Stein
Dave Stein

Reputation: 9316

Can I post a message to a window.opener

I am doing window.opener.postMessage('a=1','*') where the current window was opened via window.open.

A console.log of window.opener does show the right window but I do not see messages coming into the opener.

I am doing $(window).on( 'message', handleMessage ); where handleMessage has a console.log to know it was hit. I have done this several times for cross-iframe communication, and was hoping to achieve the same thing for my new window.

Upvotes: 3

Views: 2314

Answers (2)

Dave Stein
Dave Stein

Reputation: 9316

The issue here is the jQuery event handler. postMessage natively will work like this

function handleMessage( evt ) {
  // evt.data will be whatever was posted
}

window.addEventListener( "message", handleMessage, false );

jQuery does this:

function handleMessage( evt ) {
  // evt.data will be from jQuery where it populates from an argument in .trigger
  // evt.originalEvent.data is from the postMessage
}
$(window).on( 'message', handleMessage );

Browser compatibility should also be noted from the previous answer ( which I'm upvoting ), however the case here in Firefox/Chrome is what I've written.

Upvotes: 2

Quentin
Quentin

Reputation: 943823

From caniuse:

Partial support in IE8-9 refers to only working in frames/iframes (not other tabs/windows).

So yes, you can, but browser support is more limited.

Upvotes: 2

Related Questions