简体   繁体   中英

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

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.

ie within your iFrame have this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM