zoukankan      html  css  js  c++  java
  • postMessage的使用

    一、简介

    1、postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递

    2、postMessage(data,origin)方法接受两个参数:

    (1)data:要传递的数据,html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化,在低版本IE中引用json2.js可以实现类似效果,

    (2)origin:字符串参数,指明目标窗口的源,协议+主机+端口号[+URL],URL会被忽略,所以可以不写,这个参数是为了安全考虑,postMessage()方法只会将message传递给指定窗口,当然如果愿意也可以建参数设置为"*",这样可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/";

    二、使用

    1、子页面向父页面传递消息

    <!-- index.html -->
    <iframe src="http://127.0.0.1:5500/frame1.html" frameborder="1"></iframe>
    <iframe src="http://127.0.0.1:5500/frame2.html" frameborder="1"></iframe>
    <script>
    window.addEventListener('message',function(e){
      console.log(e.data)
    },false)
    </script>
    <!-- frame1.html -->
    <h1>iframe1 page</h1>
    <script>
      window.top.postMessage('message from iframe1');
    </script>

    2、父页面向子页面传递消息

        <!-- index.html -->
        <iframe src="http://127.0.0.1:5500/frame1.html" frameborder="1"></iframe>
        <iframe src="http://127.0.0.1:5500/frame2.html" frameborder="1"></iframe>
        <script>
            window.onload = function () {
                var frame1 = window.frames[0];
                frame1.postMessage('message from parentwindow', '*');
            }
        </script>
       <!-- frame1.html -->
        <h1>iframe1 page</h1>
        <script>
            window.addEventListener('message',function(e){
                console.log(e.data)
            },false)
        </script>

  • 相关阅读:
    Delphi下的WinSock编程
    基于Delphi使用API实现Sock通讯
    delphi7与XE的变量与函数的改变
    Delphi7·ProgressBar控件
    delphi 进度条
    delphi带包编译详解(build with runtime package)
    TList 的 quicksort 算法研究和使用。
    Delphi7升级到Delphi 2010、Delphi XE、Delphi XE2总结
    Delphi编译错误代码翻译表
    Firebird(火鸟)数据库 v3.0.3.32900官方版
  • 原文地址:https://www.cnblogs.com/EricZLin/p/10534537.html
Copyright © 2011-2022 走看看