javascript - postMessage to sandboxed iframe, why is recipient window origin null?

末鹿安然 提交于 2019-12-03 05:44:13

The problem is created by the <iframe> itself, with its sandbox attribute:

<iframe name="childFrame" class="iframed" src="child.html" sandbox="allow-scripts"></iframe>

As per the Mozilla Developer Network documentation on this element, the following gives a problem about same-origin policy:

allow-same-origin: If this token is not used, the resource is treated as being from a special origin that always fails the same-origin policy.

You didn't specified allow-same-origin, that means the frame is treated as being from a special origin, and postMessage calls to that frame will fail.

To solve the problem, just add allow-same-origin to the sandbox attribute, like this:

<!-- index.html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="childFrame" class="iframed" src="child.html" sandbox="allow-scripts allow-same-origin"></iframe>
<button class="btn1">A</button>
<button class="btn2">B</button>

<script>
$('.btn1').click(function(event) {
    // This works!
    $('.iframed')[0].contentWindow.postMessage( "something" , '*' );
});
$('.btn2').click(function(event) {
    // This will work too
    $('.iframed')[0].contentWindow.postMessage( "whatever you want" , 'https://myurl.net' );
});
</script>
<!-- child.html -->
<script type="text/javascript">
    window.onmessage = function(event) {
        console.log(event.data);
    }
</script>

That's it!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!