vue内嵌iframe跨域页面传参

背景:公司的一个平台为方便第三方平台接入页面,需要写成可以单页面引入的方式。

知识点:涉及到跨域访问页面,以及页面多余属性的隐藏

实现方式:

自己平台:

 在main.js文件里写入下面代码,监听到

import { userLogin } from "./common/user";
window.addEventListener('message', function (e) {  // 监听 message 事件
  if (e.data.name) {
    userLogin({
      username: window.name || e.data.name,
      password: window.pas || e.data.pas,
    })
      .then((data) => {
        if (data.data.code == 200) {
          let res = data.data.data;
          Cookies.set("token", res.token);
          localStorage.setItem('username', e.data.cont)
          router.push(e.data.href1)
          location.reload()
          if (e.data.href1) {
            window.parent.postMessage({ isHref: true }, '*')
          }
        } else {
          window.parent.postMessage({ isHref: true }, '*')
        }
      })
      .catch((res) => {
        ElementUI.Message({
          message: '服务异常',
          type: 'error',
          customClass: 'messageINdex'
        })
        // console.log(res);
      });
  }

});
  • window.parent 是 iframe 子页面获取父页面的 window 对象
  • 后面的 * 号就是处理跨域问题的,任何域名都不会出现跨域问题
window.parent.postMessage("需要传递的参数", '*')
  • 也可以指定传送域名地址,这个域名不会出现跨域问题,写父页面(接收)域名地址
window.parent.postMessage("需要传递的参数", 'http://0.0.0.0:8080')

第三方平台嵌入


// DOM元素
   //<div v-loading="loading加载动画变量" style="设置长宽">
      <div class="iframe_box" style="设置长宽;display:none;">
        <iframe
          id="child1"
          src="目标完整地址"
          width="width"
          height="height"
        >
        </iframe>
      </div>
   //</div> 

// JS控制显示
  // this.loading = true;
  // 获取iframe节点传递参数
      document.getElementById("child1").contentWindow.postMessage(
        {
          name: "账号",
          pas: "密码",
          href1: "路由(/main/onlineDiff)",
          cont: "携带文章",
        },
        "*"
      );


    // 页面加载好的回调
    // let _this = this;
    window.addEventListener("message", function (e) {
      // 地址如果存在
      if (e.data.isHref) {
        setTimeout(() => {
          // 页面显示,loading去除
        document.querySelector('.iframe_box').style.display='inline-block'
          // _this.loading = false;
        }, 500);
      }
    });

猜你喜欢

转载自blog.csdn.net/weixin_52691965/article/details/129161892
今日推荐