0

I need to run JavaScript inside iFrame, I understand that I must use post message to do this but I do not understand how to use it.

Site 1 is http://www.example.com/chat.html Site 2 (iFrame on Site 1) is http://www.example.com:7778

Site

$( "#link" ).click(function() {
    document.getElementById('iframe_id_here').contentWindow.postMessage({command: 'joinChannel', args: {channel: $(this).attr('data-room')}}, '*');
});

iFrame

function joinChannel(event)
{
  if (event.origin !== "http://example.com/chat.html")
    return;

  network.join(***How do I access $(this).attr('data-room')?***, '');
}

window.addEventListener("message", joinChannel, false);
user5603796
  • 369
  • 4
  • 15
  • you may want to look at [this](http://stackoverflow.com/q/364952/4340788) question? – Burki Apr 15 '16 at 14:47
  • Possible duplicate of http://stackoverflow.com/questions/1663242/calling-a-function-inside-an-iframe-from-outside-the-iframe too. – Shakespeare Apr 15 '16 at 14:49
  • Why do you have them on different ports? You can't just use the same domain and port? – putvande Apr 15 '16 at 14:50
  • @FezVrasta — No. `postMessage` doesn't require anything special on the server. Its permissions are specified in the JavaScript. – Quentin Apr 15 '16 at 14:59

1 Answers1

2

In window.postMessage, the passed message is stored in the event.data object.

In your case, the channel should be accessible via event.data.args.channel.

Steve
  • 10,435
  • 15
  • 21