D
D
Dmitry Skogorev2015-09-05 20:40:18
JavaScript
Dmitry Skogorev, 2015-09-05 20:40:18

How to send postmessage from iframe to parent?

Good day.
It is necessary to send a command from the iframe to the window in which it is launched. it seems nothing complicated and copy-paste from stackoverflow should have saved me, but nothing works,
can someone share a ready-made solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav, 2015-09-07
@vacslav-dev

In an iframe:
You can pass '*' as the second parameter to postMessage - then the message will be available for all windows.
Serialization to JSON of the first parameter is needed to support IE below either version 8 or version 9, I don’t remember exactly.
In the parent window:

function handlerMessage(e){
    var data = JSON.parse(e.data);
    var origin = e.origin;
    if(origin !== 'http://адрес_iframe'){
        return false;
    }
    // здесть можно использовать data как объект.
}
if(window.addEventListener){
    window.addEventListener('message', handlerMessage);
} else {
    window.attachEvent('message', handlerMessage);
}

The code is 100% working, from a combat project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question