javascriptiframecross-browsersendmessagepostmessage

Sending message back with postmessage


I am currently making an application where it is neccessary to send information between two domains (will be on the loading of the page).

Website 1:

Creates iFrame > Sends Postmessage to website 2

window.onload = function () {
    iframe = document.createElement('IFRAME');
    iframe.setAttribute('src', 'WEBSITE 2');
    iframe.style.width = '200px';
    iframe.style.height = '200px';
    iframe.style.border = 'none'; //please do not show the iframe JS.
    iframe.id = 'lol';

    document.body.appendChild(iframe);
    document.getElementById('test').innerHTML = 'Test!';
    window.addEventListener('message', listener, false);

    window.setTimeout(sendMessage, 100);
};

function sendMessage(e) {
    var receiver = document.getElementById('lol').contentWindow;
    receiver.postMessage('Hello Treehouse!', 'WEBSITE 2');
}

function listener(event) {
    if (event.origin !== 'WEBSITE 2') return; //website isn't ours bro

    document.getElementById('test').innerHTML = event.data;
}

Website 2

Gets Postmessage from website 1 > Create iFrame (?) > Sends Postmessage to website 1 (?)

window.onload = function createiframe() {
    window.addEventListener('message', listener, false);
};

function listener(event) {
    if (event.origin !== 'WEBSITE 1') return; //website isn't ours bro

    document.getElementById('test').innerHTML = event.data;

    window.setTimeout(createiFrame, 1000);
}

function createiFrame() {
    iframe = document.createElement('IFRAME');
    iframe.setAttribute('src', 'WEBSITE 1');
    iframe.style.width = '230px';
    iframe.style.height = '203px';
    iframe.style.border = 'none'; //please do not show the iframe JS.
    iframe.id = 'lol';
    document.body.appendChild(iframe);
    document.getElementById('test').innerHTML = 'Test!';
    window.setTimeout(sendMessage, 1000);
}

function sendMessage(e) {
    var receiver = document.getElementById('lol').contentWindow;
    receiver.postMessage('Hello ', 'WEBSITE 1');
    console.log('Message sent');
}

The iFrame is created on website 2, whereafter a loop is made with Website 1 and Website 2. The postMessage that is sent from Website 2 to Website 1 is shown in the extra iFrame. Is it possible to send a message back to website 1 which is opened in the browser?

Example of what is shown:

Test!
  Test!
    Hello 
      Test!

Solution

  • If I'm looking at this right, in Website 2 in the sendMessage() function, it looks like you are getting the newly created iframe element, and then posting a message to it. Where in reality you really want to post a message to website 1.

    From website 2...try something like

    window.parent.postMessage("hello website 1", "*");