zoukankan      html  css  js  c++  java
  • html5的postmessage实现js前端跨域訪问及调用解决方式

    关于跨域訪问。使用JSONP的方法。我前面已经demo过了。详细见http://supercharles888.blog.51cto.com/609344/856886,HTML5提供了一个很强大的API。叫postMessage。它事实上就是曾经iframe的进化版本号,使用起来极其方便,这里举个实验样例:

    我们依然依照与上文同样的设定。假定我们有2个Domain

    Domain1: http://localhost:8080  它上面有个应用叫HTMLDomain1,而且有个页面叫sender.html。

    Domain2:http://localhost:8180 它上面有个应用叫HTMLDomain2,而且有个页面叫receiver.html。

    我如今的需求是。假定Domain1上我们有个json数据,我们想让Domain2应用中的javascript要能够操作这个json 数据(注意。这里已经是跨域了,由于Domain2上的js操作了Domain1上的数据)。应该怎么办呢?

    解决方式就是用HTML5的postMessage方法

    Domain2的代码:

    首先。我们在Domain2上创建一个HTML页面,这个页面没什么内容。就一行文字会来标识它是Domain 2,它下方将来会被js用来填充从Domain1弄过来的数据。

    <!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="UTF-8"> 
    <title>Domain2上的接收者页面receiver.html</title> 
    <script type="text/javascript" src="js/receiveInfo.js"></script> 
    </head> 
    <body onload="receiveInfoFromAnotherDomain();"> 
         
         
    <p>这个页面是HTML5跨域訪问的Domain2上的页面receiver.html,它会处理来自Domain1上sender.html发送的页面</p> 
         
         
    </body> 
    </html>

    Domain2页面载入时候,它会调用receiveInfoFromAnotherDomain()函数。这个函数首先定义了一个事件监听函数,它仅仅接受来自Domain1(http://localhost:8080)的事件,否则就忽略掉,然后它从这个事件中分离出信息负载,也就是json 数据。然后显示在页面底部:

    //这个函数用于处理从Domain1上的sender发送过来的信息,然后将他们打印出来 
    function receiveInfoFromAnotherDomain(){ 
             
        console.log("entering method receiveInfoFromAnotherDomain()"); 
        //首先让window加入一个事件监听函数,表明它能够监听窗体对象的message事件 
        //它受到事件时,会先推断是否来自指定的Domain(不是全部Domain丢过来的事件它都处理的) 
        window.addEventListener("message",function(ev){ 
            console.log("the receiver callback func has been invoked"); 
                 
            //假设不是来自指定Domain的,则忽略 
            if(ev.origin !="http://localhost:8080"){ 
                console.log("the event doesn't come from Domain1!"); 
                return; 
            } 
                 
            //如今能够处理数据了 
            //控制台打印出接收到的json数据,由于我们把json字符串发送了过来 
            console.log(ev.data); 
         
            //将json字符串转为json对象。然后从中分离出原始信息 
            var personInfoJSON = JSON.parse(ev.data); 
            var name = personInfoJSON.name; 
            var title = personInfoJSON.title; 
            var info = personInfoJSON.info; 
                 
            //构造信息文本而且显示在页面的底部 
            var personInfoString="从域为: "+ev.origin+"那里传来的数据."+"<br>"; 
            personInfoString+="姓名是: "+name+"<br>"; 
            personInfoString+="头衔为:  "+title+"<br>"; 
            personInfoString+="信息为:  "+info+"<br>"; 
            document.body.innerHTML=personInfoString; 
                         
            } 
                 
        ); 
         
         
         
         
    }

    然后将Domain2 (http://localhost:8180)启动起来,不出意外。它将是:

    Domain1的代码:

    如今,我们来构建Domain1:

    为了让Domain1可以和Domain2通过事件交互,我们用了iframe,把Domain2的页面receiver.html以<iframe>形式镶嵌在Domain1的sender.html页面中。

    <!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="UTF-8"> 
    <title>Domain1上的发送者页面sender.html</title> 
    <script type="text/javascript" src="js/sendInfo.js"></script> 
    </head> 
    <body> 
         
    <p>这个页面是HTML5跨域訪问的Domain1上的页面sender.html。它将发送一些信息到Domain2上的receiver.html</p> 
    <input type="button" value="点击则发送事件到Domain2" onclick="sendInfoToAnotherDomain();"/> 
         
    <!-- 这个iframe包括了在另外一个domain->Domain2(http://localhost:8180)的接收者页面receiver.html -->
    <iframe width="1200" src="http://localhost:8180/HTML5Domain2/receiver.html"></iframe> 
    </body> 
    </html>

    同一时候我们在页面上创建一个button,当点击它就会发送json数据给Domain2.

    所以js函数就负责以json字符串形式发送json数据。然后让iframe中的Domain2页面发送信息,注意这里接受者的窗体在iframe中,所以我们用iframe.postMessage,第一个參数是我们的信息载体。这里是json字符串,第二个參数是目标Domain,也就是Domain2

    //假定这个Domain(Domain1)要把一些json信息发送到还有一个域(Domain2)的某个页面 
    function sendInfoToAnotherDomain(){ 
             
        console.log("entering method: sendInfoToAnotherDomain()"); 
             
        //首先构造一个对象,内含有我们想要发送到Domain2的信息,然后把它转为json字符串    
        var personInfo= new Object; 
        personInfo.name='charles'; 
        personInfo.title='technical lead'; 
        personInfo.info="talent man"; 
        var str=JSON.stringify(personInfo); 
             
        console.log("The information to be send: "+str); 
             
        //我们把这个json字符串发送到Domain2 
        //由于这个Domain2上的目标页面被嵌在了主页面上作为iframe,所以我们取得这个iframe然后让他来发送信息 
        //信息的内容是我们的包括个人信息内容的json字符串 
        var iframe=window.frames[0];     
        iframe.postMessage(str,'http://localhost:8180'); 
             
        console.log("json string has been sent to domain2 successfully"); 
    }

    这样一来,我们就定义了发送者(Domain1)和接收者(Domain2),发送者因为嵌了<iframe>所以页面看上去例如以下图:

    当点击"点击则发送事件到Domain2" button后,json数据信息被发送到了Domain2,由于Domain2的事件监听程序注冊了监听来自Domain1的事件,所以它能够把事件中携带的json字符串解析成原始信息,然后构造文本显示在Domain2的receiver.html的下方。如图:(能够比照sendInfoToAnotherDomain()。能够发现信息是全然匹配的)

  • 相关阅读:
    异常处理的设计和重构学习一
    设计模式之禅之六大设计原则-里氏替换原则
    设计模式之禅之六大设计原则-单一职责原则
    swagger-ui生成api文档并进行测试
    功能强大的swagger-editor的介绍与使用
    swagger-codegen自动生成代码工具的介绍与使用
    Swagger使用教程大全,从入门到精通
    Linux下MySQL的数据文件存放位置
    JUC组件扩展(三):BlockingQueue(阻塞队列)详解
    http_load的安装及使用方法
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7003282.html
Copyright © 2011-2022 走看看