|
|
@@ -0,0 +1,111 @@
|
|
|
+/*
|
|
|
+ * @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,
|
|
|
+ }, '*');
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+export default MicroFrontend;
|