Skip to content

Latest commit

 

History

History
132 lines (119 loc) · 2.78 KB

跨页面通信.md

File metadata and controls

132 lines (119 loc) · 2.78 KB

跨页面通信

同源

BroadcastChannel

// a.html
const bc = new BroadcastChannel('AlienZHOU')
bc.onmessage = function (e) {
  console.log('[BroadcastChannel] receive message:', e.data);
};
// b.html
const bc = new BroadcastChannel('AlienZHOU')
bc.postMessage('data');

LocalStorage

// a.html
window.addEventListener('storage', function (e) {
  console.log(e)
})
// b.html
localStorage.a = 1

iframe name

<!-- a.html -->
<iframe name="myIframe" src="http://localhost:1000/2.html"></iframe>
<!-- b.html -->
<script>
console.log(window.name)
</script>

iframe hash

<!-- a.html -->
<iframe name="myIframe" src="http://localhost:1000/2.html"></iframe>
<script>
var frame = document.querySelector('iframe')
frame.onload= function(){//这是异步加载的iframe
  frame.src += '#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
</script>
<!-- b.html -->
<script>
window.onhashchange = function() {
  console.log(window.location.hash)
}
</script>

postmessage

<!-- a.html -->
<iframe name="myIframe" src="http://localhost:1000/2.html"></iframe>
<script>
var frame = document.querySelector('iframe')
frame.onload= function(){//这是异步加载的iframe
  window.frames[0].postMessage('data from html1', '*');
}
</script>
<!-- b.html -->
<script>
indow.onmessage = function (e) {
  console.log(e.data, '11')
}
</script>

非同源

使用iframe作为中间桥梁

  1. a页面和b页面都嵌套bridge.html为iframe
  2. a页面触发bridge的postmessage
  3. bridge接受到postmessage,通过BroadcastChannel广播给所有都嵌套了bridge的页面
  4. 其他所有bridge都接受到广播,就调用父页面的postMessage
  5. b页面通过postMessage监听到消息
<!-- a.html -->
<iframe src="http://127.0.0.1:8082/bridge.html" frameborder="0" name="1111"></iframe>
<script>
 var frame = document.querySelector('iframe')
  frame.onload = function(argument) {
    window.frames[0].postMessage('a.html', '*');
  }

  window.onmessage = function (e) {
    console.log('a.html onmessage', e.data)
  }
</script>
<!-- b.html -->
<iframe src="http://127.0.0.1:8082/bridge.html" frameborder="0" name="1111"></iframe>
<script>
  window.onmessage = function (e) {
    console.log('a.html onmessage', e.data)
  }
</script>
<!-- bridge.html -->
<iframe src="http://127.0.0.1:8082/bridge.html" frameborder="0" name="1111"></iframe>
<script>
  const bc = new BroadcastChannel('AlienZHOU')
  
  // 收到来自页面的消息后,在 iframe 间进行广播
  window.addEventListener('message', function (e) {
    console.log(e, 'bridge')
    bc.postMessage(e.data);
  });

  bc.onmessage = function (e) {
    window.parent.postMessage(e.data, '*');
  }
</script>