MicroFrontend.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /*
  2. * @Author: sjl
  3. * @Date: 2023-04-26 10:55:12
  4. * @Descripttion:
  5. */
  6. class MicroFrontend {
  7. constructor() {
  8. this.apps = {}; // 存储子应用的信息
  9. this.globalData = {}; // 存储全局数据
  10. this.init();
  11. }
  12. // 初始化方法
  13. init() {
  14. // 监听子应用的消息
  15. window.addEventListener('message', (event) => {
  16. console.log('父消息:', event);
  17. const { data, source } = event;
  18. if (data.type === 'register') {
  19. // 子应用注册
  20. this.apps[data.name] = {
  21. source,
  22. loaded: false,
  23. };
  24. } else if (data.type === 'logout') {
  25. if (globalEvent.wlwLogin) {
  26. globalEvent.wlwLogin();
  27. globalEvent.wlwLogin = null;
  28. }
  29. } else if (data.type === 'js') {
  30. eval(data.message);
  31. } else if (data.type === 'loaded') {
  32. // 子应用加载完成
  33. this.apps[data.name].loaded = true;
  34. } else if (data.type === 'setGlobalData') {
  35. // 设置全局数据
  36. this.globalData[data.key] = data.value;
  37. } else if (data.type === 'getGlobalData') {
  38. // 获取全局数据
  39. const value = this.globalData[data.key];
  40. source.postMessage(
  41. {
  42. type: 'getGlobalData',
  43. key: data.key,
  44. value,
  45. },
  46. '*'
  47. );
  48. }
  49. });
  50. return this;
  51. }
  52. // 注册子应用
  53. register(name, id, url, callback) {
  54. const iframe = document.createElement('iframe');
  55. iframe.src = url;
  56. iframe.style.width = '100%';
  57. iframe.style.height = '100%';
  58. document.getElementById(id).appendChild(iframe);
  59. this.apps[name] = {
  60. source: iframe.contentWindow,
  61. loaded: false,
  62. };
  63. // 发送注册消息给子应用
  64. // iframe.contentWindow.postMessage({
  65. // type: 'register',
  66. // name,
  67. // }, '*');
  68. iframe.onload = function () {
  69. callback && callback();
  70. };
  71. }
  72. // 发送消息给子应用
  73. sendToApp(name, message) {
  74. const app = this.apps[name];
  75. // if (app && app.loaded) {
  76. if (app) {
  77. app.source.postMessage(message, '*');
  78. }
  79. }
  80. // 设置全局数据
  81. setGlobalData(key, value) {
  82. this.globalData[key] = value;
  83. // 发送设置全局数据的消息给所有子应用
  84. Object.values(this.apps).forEach((app) => {
  85. if (app.loaded) {
  86. app.source.postMessage(
  87. {
  88. type: 'setGlobalData',
  89. key,
  90. value,
  91. },
  92. '*'
  93. );
  94. }
  95. });
  96. }
  97. // 获取全局数据
  98. getGlobalData(key) {
  99. // 发送获取全局数据的消息给所有子应用
  100. Object.values(this.apps).forEach((app) => {
  101. if (app.loaded) {
  102. app.source.postMessage(
  103. {
  104. type: 'getGlobalData',
  105. key,
  106. },
  107. '*'
  108. );
  109. }
  110. });
  111. }
  112. }