Martyn Ball
Martyn Ball

Reputation: 4885

postMessage to parent, parent code not running

I have seen loads of examples and I can't see where i'm going wrong. But my event listener isn't running at all within the parent. Event if I post a message manually within the iframe console scope.

iframe:

$(".open").click(function() {
        window.parent.postMessage('navigated', '*', []);

parent:

window.addEventListener("load", function () {
    document.querySelectorAll('iframe[src*="forms.localhost"]').forEach(iframe => {
        iframe.addEventListener('message', (event) => {
            console.log('event');
        });
    });

I have checked and the querySelector is finding my iframe.

Upvotes: 0

Views: 1153

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

Your parent window should listen for messages on the parent window, not on the iframe elements. A single handler will receive messages from all of the iframes; you can differentiate them by the origin on the message.

Upvotes: 1

Related Questions