背景
接手了一个老项目,甲方要求在项目根页面增加tab栏切换功能,项目的子页面是通过iframe嵌套,点击子页面中的导航框可跳转到对应的页面.那么问题来了,点击子页面中的导航框跳转到对应的子页面时,根页面的tab栏样式如何实现同步切换呢?
解决方案(摘录至菜鸟教程)
postMessage() 方法用于安全地实现跨源通信。
otherWindow.postMessage(message, targetOrigin, [transfer]);
- otherWindow:其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。
- message:将要发送到其他 window的数据。
- targetOrigin:指定哪些窗口能接收到消息事件,其值可以是 *(表示无限制)或者一个 URI。
- transfer:可选,是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
实现代码
新建index.html文件
<!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>Document</title>
</head>
<body>
<div>
<h1>根页面</h1>
<iframe src="children.html" frameborder="0" width="800px" height="800px"></iframe>
</div>
</body>
<script>
window.addEventListener('message', function (e) {
console.log('index:', e);
})
</script>
</html>
新建children.html文件
<!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>Document</title>
</head>
<body>
<div class="children">
<h1>子页面</h1>
<iframe src="son.html" frameborder="0"></iframe>
</div>
</body>
</html>
新建son.html文件
<!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>Document</title>
</head>
<body>
<h1>son页面</div>
<button id="demoBtn">发送</button>
</body>
<script src="son.js"></script>
</html>
新建son.js文件
document.getElementById('demoBtn').onclick = function () {
var postUrl = location.origin
top.postMessage('这个是我传的消息', postUrl)
}
点击按钮的结果:index: MessageEvent {isTrusted: true, data: '这个是我传的消息', origin: 'http://127.0.0.1:5500', lastEventId: '', source: Window, …}
结语
既然信息已经送到,剩下的就交给你了。提枪上马,干!