为什么我的postMessage无法正常工作?

时间:2017-12-08 09:16:06

标签: javascript iframe postmessage

我有一个包含iframe元素的索引页面,这个iframe引用另一个DOMAIN页面。 我需要从iframe页面获取数据,所以我应用了postmessage概念。 但它不起作用。

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Using PostMessage for Cross-Domain Access to an Iframe</title>
<meta name="description" content="Example demonstrates using postMessage to interact with an iframe on another domain and obtain information about its objects and properties." />
<script type="text/javascript">
// check for browser support
if ( window.addEventListener ) {

    // when DOM is ready assign button onclick handlers
    window.addEventListener('DOMContentLoaded', function() {
        // where to send messages with postMessage
        var target_origin = 'Myiframe.html';

        // get reference to form to attach button onclick handlers
        var form = document.getElementById('demoForm');
        // get reference to iframe window
        var win = document.getElementById('ifrm').contentWindow;

        // set height of iframe and display value
        form.elements.button1.onclick = function() {
            var ifrm = document.getElementById('ifrm');
            var ht = ifrm.style.height = '160px';
            this.form.display.value = 'The iframe\'s height is: ' + ht;
        }

        // to increment and display counter variable in iframed document
        form.elements['button2'].onclick = function() {
            win.postMessage( {'task': 'ctr'}, target_origin );
        }

        // to get value of form element in iframed document
        form.elements.button3.onclick = function() {
            win.postMessage( {'task': 'val'}, target_origin );
        }

        // to invoke function in iframed document
        form.elements.button4.onclick = function() {
            win.postMessage( {'task': 'clear'}, target_origin );
        }

    }, false);

    // message handler
    window.addEventListener('message', function (e) {
        // check message origin
        if ( e.origin === 'Myiframe.html' ) {
            var task = e.data['task']; // task received in postMessage
            // get reference to demo form
            var form = document.getElementById('demoForm');

            switch ( task ) { // postMessage tasks
                // display counter received in postMessage
                case 'ctr' :
                    form.display.value = 'counter in iframe is: ' + e.data['counter'];
                    break;

                // display text box value received in postMessage
                case 'val' :
                    form.display.value = 'The greeting is: ' + e.data['val'];
                    break;

                case 'clear' :
                    // nothing to do for this one
                    break;
                //default:

            }
        }
    }, false);


} 
</script>
</head>
<body>
<form id="demoForm" action="#">
    <p>
        <input name="button1" type="button" value="Button 1" />
        <input name="button2" type="button" value="Button 2" /> 
        <input name="button3" type="button" value="Button 3" /> 
        <input name="button4" type="button" value="Button 4" /> 
    </p>
    <p><input type="text" name="display" size="30" readonly="readonly" /></p>
</form>
<iframe name="ifrm" id="ifrm" src="Myiframe.html"></iframe>
</body>
</html>

Myiframe.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>untitled</title>
<meta name="robots" content="noindex" />
<script type="text/javascript">
// example variable and function for cross-document demo
counter = 0; 
function clearGreeting() {
    document.forms['iframeDemoForm'].elements['greeting'].value = '';
}

// check for browser support
if ( window.addEventListener ) {
    // message handler
    window.addEventListener('message', function(e) {
        // check message origin

        if ( e.origin === 'index.html' ) {
            var task = e.data['task']; // task received in postMessage
            var msg; // for postMessage reply to e.source 

            switch ( task ) { // postMessage tasks
                // increment counter variable and send
                case 'ctr' :
                    msg = { 'task': 'ctr', 'counter': ++counter };
                    e.source.postMessage(msg , e.origin );
                    break;

                // send value of entry in text box (validate first)
                case 'val' :
                    var re = /[^-a-zA-Z!,'?\s]/g; // to filter out unwanted characters
                    var fld = document.forms['iframeDemoForm'].elements['greeting'];
                    var val = fld.value.replace(re, '');
                    var msg = {'task': 'val', 'val': val};
                    e.source.postMessage(msg , e.origin );
                    break;

                // clear text box by calling function
                case 'clear' :
                    clearGreeting();
                    break;

                //default:
            }
        }
    }, false);
}
</script>
</head>
<body>

<h1>Iframe</h1>

<ul>
    <li>Button 1 sets iframe style height</li>
    <li>Button 2 increments global variable in iframed document</li>
    <li>Button 3 transfers Greeting below to text box above iframe</li>
    <li>Button 4 clears Greeting text box below (calls function in iframe)</li>
</ul>

<form action="#" id="iframeDemoForm">
    <label for="greeting">Enter a Greeting: </label>
    <input type="text" name="greeting" id="greeting" value="Hello there!" />
</form>

<script type="text/javascript">
(function() {

    // disable submission of all forms on this page
    for (var i=0, len=document.forms.length; i<len; i++) {
        document.forms[i].onsubmit = function() { return false; };
    }

}());
</script>


<p id="demoInfo"><span class="news">Note</span>: This page is part of a tutorial on postMessage and is intended to display in an iframe. <a href="http://www.dyn-web.com/tutorials/iframes/postmessage/access/iframe.php">Click here</a> to see it in its proper context.</p>

<script type="text/javascript">
// if not in iframe, display link to tutorial
if ( self === top ) {
    document.getElementById('demoInfo').style.display = 'block';
}
</script>

</body>
</html>

当buttoon被解雇时,我应用了一些操作,除了第一个按钮之外什么也行不通。 我犯了什么错误并引导我plz

1 个答案:

答案 0 :(得分:0)

未正确指定目标原点。 请在此处参考原产地规格https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

  

调用postMessage时发送消息的窗口的来源。此字符串是协议和“://”的串联,如果存在,则为主机名,如果存在端口,则“:”后跟端口号,并且与给定协议的默认端口不同。典型来源的示例是https://example.org(暗示端口443),http://example.net(暗示端口80)和http://example.com:8080。请注意,此源不保证是该窗口的当前或未来来源,自从调用postMessage以来,该窗口可能已导航到其他位置。