HTML5socket通信——postMessage出现的不能提交的问题

前几天写了HTML5的俄罗斯方块,其实也不是想好好练一下HTML5,其实真正是想把HTML5的socket通信功能好好熟悉一下,当然喽,下一步也就是HTML5俄罗斯方块的网络对战版,敬请期待哦(网址http://www.9k6.net/games

今天尝试了一下html5的postMessage功能,一度出现了代码出错的问题,结合出现的错误,在这里给大家分享一下,以便大家遇到类似问题时不会抓耳挠腮~~

两个页面,index.html和inner.html,其中在index中使用iframe调用inner.html页面。最初写的代码如下(出错的代码

index.html

View Code
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>Communication</title>
 6     <script type="text/javascript">
 7         function $$(id){
 8             return document.getElementById(id);
 9         }
10         function sendMess(){
11             var str = 'Yes,you are right';
12             var targetOrigin = 'localhost';
13             var win = $$('inner1').contentWindow;
14             win.postMessage(str,targetOrigin);
15         }
16     </script>
17 </head>
18 <body>
19     <div>
20         <input type="button" onclick="sendMess();">
21     </div>
22     <iframe id="inner1" src="inner.html"></iframe>
23 </body>
24 </html>

inner.html

View Code
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <script type="text/javascript">
 6             function getMess(){
 7                 window.addEventListener('message',function(e){
 8                     alert(e.origin);
 9                     if (e.origin == 'http://localhost') {
10                         alert(e.data);
11                     };
12                 })
13             }
14         </script>
15     </head>
16     <body onload="getMess();">
17     </body>
18 </html>

将这两句代码放入本地的apache目录中,然后打开Chrome和firefox调试,结果bug~~~

Chrome和firefox的出错信息如下:

Chrome:Uncaught Error: SYNTAX_ERR: DOM Exception 12

firebug:SyntaxError: An invalid or illegal string was specified

最后,开始狂找google+百度,最后看人家的origin都是*,索性尝试一下也改成了*,结果真的OK了~~~

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Communication</title>
    <script type="text/javascript">
        function $$(id){
            return document.getElementById(id);
        }
        function sendMess(){
            var str = 'Yes,you are right';
            var targetOrigin = '*';
            var win = document.getElementById('inner1').contentWindow;
            win.postMessage(str,targetOrigin);
        }
    </script>
</head>
<body>
    <div>
        <input type="button" onclick="sendMess();">
    </div>
    <iframe id="inner1" src="inner.html"></iframe>
</body>
</html>

debug N久,就以为一个*啊????!!当时那个表情啊~~

后来尝试了一下,发现localhost作为origin是不行的,需要使用http://localhost(写origin时一定要加上http,本例也是一样的)。

总结一下原因,就是postMessage的origin是http://localhost而不是localhost,如果使用了不正确的origin,注定会出错!!

原文地址:https://www.cnblogs.com/picaso/p/2811529.html