Vue前端嵌套系统实现在iframe框架中传值给子系统实现单点登录或其他操作

PinkM∞n7 2024-06-13 14:03:03 阅读 74

        最近做到的项目里遇到了这样一个问题:由于不同的组件写在了不同的项目中,需要引用的时候一般是通过iframe框架直接在父系统中引用已经上传好了的网址,通过iframe进行操作。当iframe中只有浏览等无关用户、用户权限时,直接引用框架是没有影响的,但是如果要对用户进行区分,则还需要将父系统的登录用户信息传递给子系统使用。

        综上需要实现的效果就是取消子系统的登陆跳转,将token或其他值传入子系统中,使得在iframe加载后自动登录了父系统的账号。在实现的过程中试过如下几种方式都较为简单的能够使iframe嵌套内容和父系统传递信息。

1.通过url携带"不重要"或者'token'的信息传递给子页面

        在A系统中传递token/params信息:

 <iframe id="iframe" class="iframe" :src="iframeUrl"></iframe>

 iframeUrl() {

      let token= "*******";

      return `${window.iframeUrl}/#/网页url/${token}`

 }

        B系统中接受token/params信息:

可以在单页面使用:

  if (this.$route.query.token) {

   setToken(token)  //将token值按照子系统保存下来 

      }

也可以在路由守卫,router.beforeEach()函数添加

{

setToken(token)  //将token值按照子系统保存下来 

window.location.href = window.location.origin

}

2.通过postMessage/addEventListener传递信息

在嵌入子系统的父页面中设置传送信息的代码

const iframe = document.querySelector("#iframe"); //首先获取到需要发送信息的框架 const iframeWindow = iframe.contentWindow; //传递保存在父框架中的信息 const token = localStorage.getItem("token"); const userId = localStorage.getItem("userId"); const userName = localStorage.getItem("userName");     //当框架加载时,传送信息到框架中 iframe.onload = () => { iframeWindow.postMessage({ token: token, userId: userId, userName: userName }, "http://localhost:9000/网页路由"); //postMessage的第一个参数是传递的信息,第二个参数是接收信息的地址,也可以设置为*则所有嵌入该页面的iframe都能接收到信息 };

在子页面中设置接收信息的代码,在created或mounted里调用方法接收信息

window.addEventListener("message", (event) => {        if (event.data.token) {//将数据存储到子系统的localStorage中          localStorage.setItem("token", event.data.token);          localStorage.setItem("userId", event.data.userId);          localStorage.setItem("userName", event.data.userName);    //使用传递的信息          this.param.createUser = event.data.userId;              }      });

同理,如果我要在子页面发送消息给父页面进行操作,操作当如下

parentUpcd() { this.reback = true; let params = { fromImport: this.fromImport, reback: this.reback }; // 发送信息给父页面,父页面返回至上一页 window.parent.postMessage(params, "*"); },

父页面中mounted接受子页面传递信息

window.addEventListener("message", (e) => { this.reback = e.data.reback; this.fromImport = e.data.fromImport; });

3.父域Cookie(该方法需要应用系统的域名建立在一个共同的主域名下)

Cookie 的作用域由 domain 属性和 path 属性共同决定.domain 属性的有效值为当前域或其父域的域名/IP地址,path 属性的有效值是以“/”开头的路径.

当将 Cookie 的 domain 属性设置为当前域的父域,就认为它是父域 Cookie,即父域中的 Cookie 子域能共享,所以子域会自动继承父域中的Cookie.

所以我们只需要将 Cookie 的 domain 属性设置为父域的域名(主域名),同时将 Cookie 的 path 属性设置为根路径,这样所有的子域应用就都可以访问到这个 Cookie 了.



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。