使用iframe来解决大部分web项目的兼容性问题

木头的喵喵拖孩

工作中遇到一个需求,要在一个比较老的 web 项目中添加新功能,但是最好不要动老项目的代码。
思来想去,就用 iframe 来实现吧,iframe 的内容和老项目的内容互不干扰,数据传输使用 postMessage 来实现。
github地址
npm地址

代码

  • IframeMsg.js 核心类(封装发送和接收信息的逻辑)
  • index.html 父页面
  • child.html 子页面

IframeMsg.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class IframeMsg extends EventTarget {
data; // 接收到的信息

/**
* 通信对方的window对象
* @param {Window} _window
*/
constructor(_window) {
super();
this._window = _window;
this.init();
}

/**
* 初始化接收信息处理函数
*/
init() {
const onMessage = (ev) => {
if (ev.data) {
const { action, data } = ev.data;
if (action === undefined) return;
this.data = ev.data;
this.dispatchEvent(new Event('message'));
}
};
window.addEventListener('message', onMessage, false);
}

/**
* 发送消息
* @param {String} action 动作
* @param {any} data 消息体
*/
send(action, data) {
this._window.postMessage(
{
action,
data
},
'*'
);
}
}

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>iframe通信</title>
</head>

<body>
<iframe id="child" src="./child.html" frameborder="0"></iframe>

<script src="./IframeMsg.js"></script>
<script>
let child = document.getElementById('child');

child.onload = function () {
let iframeMsg = new IframeMsg(child.contentWindow);

iframeMsg.send('jump', '这条信息从父window发送到子window');
iframeMsg.addEventListener('message', (ev) => {
console.log(ev.target.data);
alert(JSON.stringify(ev.target.data));
});
};
</script>
</body>
</html>

child.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>iframe通信</title>
</head>

<body>
<script src="./IframeMsg.js"></script>
<script>
let iframeMsg = new IframeMsg(window.parent);
iframeMsg.addEventListener('message', (ev) => {
console.log(ev.target.data);
alert(JSON.stringify(ev.target.data));
});
setTimeout(() => {
iframeMsg.send('jump', '这条信息从子window发送到父window');
}, 1000);
</script>
</body>
</html>
  • 标题: 使用iframe来解决大部分web项目的兼容性问题
  • 作者: 木头的喵喵拖孩
  • 创建于: 2023-07-27 14:06:46
  • 更新于: 2024-05-21 10:56:15
  • 链接: https://blog.xx-xx.top/2023/07/27/使用iframe来解决大部分web项目的兼容性问题/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
此页目录
使用iframe来解决大部分web项目的兼容性问题