parent.html 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>父页面</title>
  6. </head>
  7. <body>
  8. <h2>父页面</h2>
  9. <button id="sendBtn">向 iframe 发送消息</button>
  10. <!-- 注意:src 必须是同源或你明确知道目标 origin -->
  11. <iframe id="myIframe" src="child.html" width="600" height="300"></iframe>
  12. <script>
  13. const iframe = document.getElementById('myIframe');
  14. const sendBtn = document.getElementById('sendBtn');
  15. // 等待 iframe 加载完成再发送消息更安全
  16. iframe.onload = () => {
  17. console.log('iframe 已加载');
  18. };
  19. sendBtn.addEventListener('click', () => {
  20. const data = {
  21. message: '你好,子页面!',
  22. userId: 12345,
  23. timestamp: new Date().toISOString()
  24. };
  25. // 向 iframe 发送消息
  26. // 第二个参数是目标 origin,出于安全考虑建议不要用 '*'
  27. // 如果 child.html 在同一域名下,可以用 window.location.origin
  28. console.log('向 iframe 发送消息:', data);
  29. iframe.contentWindow.postMessage(data, window.location.origin);
  30. });
  31. </script>
  32. </body>
  33. </html>