PostMessage H5跨域

873 阅读2分钟

是什么:

在HTML5中新增了postMessage方法,postMessage可以实现跨文档消息传输(Cross Document Messaging),Internet Explorer 8, Firefox 3, Opera 9, Chrome 3和 Safari 4都支持postMessage。

具体能干嘛

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

实际应用

一个大的系统里面嵌套了两个子系统,只有这个大的系统里面有登录功能,每一个子系统里面的具体权限也是由父系统传递过来

问题

存在H5跨域,子系统不能直接拿到扶系统携带的用户信息

解决

利用PostMessage

具体实现代码:

  • 首先父系统里面:
<div>

    <iframe
      id="IframeId"
      :src="link"
      frameborder="0"
      class="iframe iframeConatiner"
      seamless
      v-show="ifameFlag"
    ></iframe>

    <div class="noIfameshow_container" v-show="!ifameFlag">
      <span class="el-icon-loading"></span>正在加载中,请稍后...
    </div>

  </div>
    // 一:父子页面通信,测试父页面向子页面发送数据
    //获取iframe
    const iframe = document.getElementById("IframeId");
    setTimeout(() => {
      iframe.contentWindow.postMessage("父页面的数据", "http://localhost:8084/");
      this.ifameFlag = true;
    }, 1000);
    // 二:父子页面通信,测试父页面向子页面发获取数据
    // 主页面监听message事件,可以拿到子页面传递回来的数据
    window.addEventListener("message", function(e) {
        console.log(e.data);
        // switch (e.data) {
        //   case 'elFormRule':
        //     that.$router.push({name: "ElFormRule"})
        // }
    }, false);
  • 子系统里面:
// 测试postMessage:测试通信,这里拿到父页面的数据:start
// 父页面的地址:
const fatherBaseUrl = "http://localhost:8083/";
Vue.prototype.$fatherBaseUrl = fatherBaseUrl;
bind(window, 'message', function (e) {
  var e = window.event || arguments[0];
  if (e.source != window.parent) return;
  // 这里对于store开启了模块化之后的巩固,如何访问模块里面的state,mutations:
  // 通过这样的方式可以访问开启了模块化的state:##############
  // console.log(store.state.module02.getFatherData);
  // 通过这样的方式可以访问开启了模块化的mutations:##########
  // store.commit('module01/NUMADD', 10000);
  // 拿到父页面的数据并加入store:
  store.commit('module02/SET_GETFATHERDATA', e.data);
  // 向父页面发送数据:
  window.parent.postMessage('子页面的数据', fatherBaseUrl);
})
// 绑定事件的兼容性处理:
function bind(obj, evname, fn) {
  if (obj.addEventListener) {
    obj.addEventListener(evname, fn, false);
  } else {
    obj.attachEvent("on" + evname, function () {
      fn.call(obj);
    })
  }
}
// 测试postMessage:测试通信,这里拿到父页面的数据:end

好了,到这里就结束了,感谢你的浏览