The Web is built on the basis of the same origin policy. The same origin policy is the behavior of the browser to protect the local data from being contaminated by the data retrieved by JavaScript code. Therefore, it intercepts the data received after the request sent by the client. We can use iframe to enable different domains to request resources from each other.
homologous
- Concept: Same protocol, same domain name, same port
- Objective: To ensure the security of user information and prevent user data leakage
- Scope of limitation:
- Cookie, LocalStorage, and IndexDB cannot be read
- Dom not available
- AJAX requests have cross-domain limitations on the browser side
iframe
Basic attributes
- The SRC iframe address
- Name the name of the iframe
- width
- height
- Frameborder No Displays the border around the frame
- 1 have a border
- 0 no border
- Scrolling indicates whether to display the scroll bar in iframe
- yes
- no
- auto
postMessage
PostMessage is a new API introduced in HTML5 that enables cross-window and cross-domain communication by binding the Window’s Message event.
Application scenarios
- Data transfer between the page and the new window it opens
- Page messaging with nested iframes
- Messaging between multiple Windows
Iframe + postMessage is used
Export default class Demo {constructor() {this.iframeurl = "https://www.a.com"} componentDidMount() {// Listen for the message event window.addEventListener("message", this.receiveMessage, false); } /* receiveMessage = (event) => {const {type, data} = event.data; Console. log(" get type + type + "and data + "data" from son); } /* Send messages */ sendMessage = () => {// For security, always specify the exact destination when using postMessage to send data to other Windows, * window.frames[0]. PostMessage ({type: 'sendMessageToSon'}, 'https://www.b.com'); } render(){ return <div> <iframe src={this.iframeUrl} frameBorder="0" width="800px" height="90%"/> <button OnClick ={this.sendMessage}> Send a message to the parent window </button> </div>}}Copy the code
<script> // Listen for message events and receive messages window.addEventListener("message", receiveFatherMessage, false); // Add event handler function receiveFatherMessage (event) {// For security, if you want to receive messages from other sites, Always verify the sender's identity with the Origin and source attributes if(Event.origin! == 'https://www.baidu.com') return; Console. log(' THIS is Son, I received: ', event.data); } sendMessage() { const value = document.getElementById("message").value; window.parent.postMessage(value, "*"); </script> <body> <input type="text" id="message"/> <button onclick="sendMessage()"Copy the code