MicroFrontend.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. type: 'getGlobalData',
  42. key: data.key,
  43. value,
  44. }, '*');
  45. }
  46. });
  47. return this;
  48. }
  49. // 注册子应用
  50. register(name,id,url,callback) {
  51. const iframe = document.createElement('iframe');
  52. iframe.src = url;
  53. iframe.style.width="100%";
  54. iframe.style.height="100%";
  55. document.getElementById(id).appendChild(iframe);
  56. this.apps[name] = {
  57. source: iframe.contentWindow,
  58. loaded: false,
  59. };
  60. // 发送注册消息给子应用
  61. // iframe.contentWindow.postMessage({
  62. // type: 'register',
  63. // name,
  64. // }, '*');
  65. iframe.onload = function() {
  66. callback && callback()
  67. };
  68. }
  69. // 发送消息给子应用
  70. sendToApp(name, message) {
  71. const app = this.apps[name];
  72. // if (app && app.loaded) {
  73. if (app) {
  74. app.source.postMessage(message, '*');
  75. }
  76. }
  77. // 设置全局数据
  78. setGlobalData(key, value) {
  79. this.globalData[key] = value;
  80. // 发送设置全局数据的消息给所有子应用
  81. Object.values(this.apps).forEach((app) => {
  82. if (app.loaded) {
  83. app.source.postMessage({
  84. type: 'setGlobalData',
  85. key,
  86. value,
  87. }, '*');
  88. }
  89. });
  90. }
  91. // 获取全局数据
  92. getGlobalData(key) {
  93. // 发送获取全局数据的消息给所有子应用
  94. Object.values(this.apps).forEach((app) => {
  95. if (app.loaded) {
  96. app.source.postMessage({
  97. type: 'getGlobalData',
  98. key,
  99. }, '*');
  100. }
  101. });
  102. }
  103. }