John Smith
John Smith

Reputation: 6197

Javascript, postMessage to Iframe

<body onload="onload();">

function onload()
{
    document.onkeypress = function(e) {
        //e.preventDefault(); // Prevent any default browser behaviour.
        console.log('send: '+e);
        document.getElementById('iframe').contentWindow.postMessage ('Hello Treehouse!', '*my*');
    }
    window.addEventListener('message', function(event) { console.log('get: '+event); }, false);
}
</script>

I want to forward keypresses to iframe but so far it doesnt work, iframe doesnt receive the messages

Upvotes: 0

Views: 252

Answers (1)

FunnyLookinHat
FunnyLookinHat

Reputation: 579

It looks like you're trying to bind the event listening within the same window as the sender, when you actually need that within the iFrame itself.

i.e. within your iFrame have this code:

<script>
    window.addEventListener('message', function(event) { console.log('get: '+event); }, false);
</script>

Upvotes: 2

Related Questions