otherWindow.postMessage(message, targetOrigin, [transfer])方法实现 与iframe通信

*IE有兼容问题

api参考MDN

index.html页面

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .green {
  10. padding: 10px;
  11. border: 1px solid green;
  12. margin-bottom: 20px;
  13. }
  14. #frame {
  15. width: 100%;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div class="green">
  21. <p> 父页面信息</p>
  22. <button id='btn'>向子传参</button>
  23. <div id='yy'>
  24. </div>
  25. </div>
  26. <iframe src="./frame.html" id="frame" frameborder="0"></iframe>
  27. <script>
  28. var yy = document.querySelector('#yy')
  29. // 父页面接收子页面的参数
  30. window.addEventListener('message', function (e) {
  31. console.log(e)
  32. yy.innerHTML = e.data.a
  33. })
  34. // 父页面传给子页面的参数
  35. var btn = document.querySelector('#btn')
  36. btn.addEventListener('click', function (e) {
  37. var contentWindow = document.querySelector('#frame').contentWindow
  38. contentWindow.postMessage({ b: '父传给子的' }, '*')
  39. })
  40. </script>
  41. </body>
  42. </html>

frame.html页面

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .red {
  10. padding: 10px;
  11. border: 1px solid red;
  12. }
  13. body{
  14. margin: 0;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div class="red">
  20. <p>子页面信息</p>
  21. <button id='btn'>向父传参</button>
  22. <div id="p">
  23. </div>
  24. </div>
  25. <script>
  26. var btn = document.querySelector('#btn')
  27. btn.addEventListener('click', function (e) {
  28. // 子页面向父传参数
  29. window.parent.postMessage({ a: '子页面传给父页面的' }, '*')
  30. // window.open('https://www.baidu.com/')
  31. })
  32. var p = document.querySelector('#p')
  33. //子页面接收父页面的参数
  34. window.addEventListener('message', function (e) {
  35. p.innerHTML = e.data.b
  36. })
  37. </script>
  38. </body>
  39. </html>