| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- /*
- * @Author: sjl
- * @Date: 2023-04-26 10:55:12
- * @Descripttion:
- */
- class MicroFrontend {
- constructor() {
- this.apps = {}; // 存储子应用的信息
- this.globalData = {}; // 存储全局数据
- this.init();
- }
-
- // 初始化方法
- init() {
- // 监听子应用的消息
- window.addEventListener('message', (event) => {
- // console.log("父消息:",event);
- const { data, source } = event;
- if (data.type === 'register') {
- // 子应用注册
- this.apps[data.name] = {
- source,
- loaded: false,
- };
- } else if (data.type === "logout") {
- if(globalEvent.wlwLogin){
- globalEvent.wlwLogin();
- globalEvent.wlwLogin = null;
- }
- } else if (data.type === "js") {
- eval(data.message)
- } else if (data.type === 'loaded') {
- // 子应用加载完成
- this.apps[data.name].loaded = true;
- } else if (data.type === 'setGlobalData') {
- // 设置全局数据
- this.globalData[data.key] = data.value;
- } else if (data.type === 'getGlobalData') {
- // 获取全局数据
- const value = this.globalData[data.key];
- source.postMessage({
- type: 'getGlobalData',
- key: data.key,
- value,
- }, '*');
- }
- });
- return this;
- }
-
- // 注册子应用
- register(name,id,url,callback) {
- const iframe = document.createElement('iframe');
- iframe.src = url;
- iframe.style.width="100%";
- iframe.style.height="100%";
- document.getElementById(id).appendChild(iframe);
- this.apps[name] = {
- source: iframe.contentWindow,
- loaded: false,
- };
- // 发送注册消息给子应用
- // iframe.contentWindow.postMessage({
- // type: 'register',
- // name,
- // }, '*');
- iframe.onload = function() {
- callback && callback()
- };
- }
-
- // 发送消息给子应用
- sendToApp(name, message) {
- const app = this.apps[name];
- // if (app && app.loaded) {
- if (app) {
- app.source.postMessage(message, '*');
- }
- }
-
- // 设置全局数据
- setGlobalData(key, value) {
- this.globalData[key] = value;
- // 发送设置全局数据的消息给所有子应用
- Object.values(this.apps).forEach((app) => {
- if (app.loaded) {
- app.source.postMessage({
- type: 'setGlobalData',
- key,
- value,
- }, '*');
- }
- });
- }
-
- // 获取全局数据
- getGlobalData(key) {
- // 发送获取全局数据的消息给所有子应用
- Object.values(this.apps).forEach((app) => {
- if (app.loaded) {
- app.source.postMessage({
- type: 'getGlobalData',
- key,
- }, '*');
- }
- });
- }
- }
-
|