How do pages embed iframe

It’s very simple. Just use it

<div style="">
    <iframe src="Address of item to reference" style=""></iframe>
</div>
Copy the code

Note that the iframe comes with a 2px border, which can be customized with style

How to communicate

So first of all, the first trouble we’re going to get into here is the cross-domain problemwindowObject has apostMessageMethod is specially used to solve cross-domain communication problems.

  • Looking at the first usage scenario, there is currently oneiframePage.html(a) andindex.html(Parent) page
<! -- index.html --><body style="border:5px solid #333;">

  <h1>this is index</h1>

  <iframe src="./iframePage.html" id='myframe'></iframe>

</body>
Copy the code
<! -- iframePage --><body style="border:5px solid #333;">

  <h1>this is iframePage</h1>

</body>
Copy the code
  1. The parent page sends data to the child page
// idnex.html

// Get the iframe element
iFrame = document.getElementById('myframe')

// Send the message after the iframe is loaded. Otherwise, the sub-page will not receive the message
iFrame.onload = function(){

  // Iframe sends a message immediately after loading
  iFrame.contentWindow.postMessage('MessageFromIndex1'.The '*');

}
Copy the code

PostMessage is mounted on the window object, so after iframe is loaded, use ifame. ContentWindow to get the Window object of iframe, and then call postMessage, which is equivalent to sending a message to the child page. The first argument to the postMessage method is the data to send, which can be any primitive type of data. The second parameter postMessage can be used to set the URL to be sent to. If the URL of the current sub-page is inconsistent with the configured url, the message will fail to be sent. We set this parameter to *, indicating that all urls are allowed to be sent.

Child pages receive data

// iframePage.html
window.addEventListener('message'.(e) = > {
    console.log("Data received:", e)
})
Copy the code



This completes the parent page to child page communication

2. Child page => Parent page

// iframePage.html
window.parent.postMessage({msg: 'MessageFromIframePage'}, The '*')
Copy the code
// index.html
window.addEventListener('message'.(e) = > {
    console.log("Data received:", e)
})
Copy the code

postMessageYou can send object types, so it’s pretty easy to use