Hello, everyone, I am quick frozen fish 🐟, a river front πŸ’¦, like the colorful πŸ’, continuous sand sculpture 🌲, is the good brother of the cold grass of the next door. Welcome to add my wechat: Sudongyuer pull you into the group, discuss together, look forward to growing together with you πŸ₯‚.

Read this article πŸ¦€

1. How to communicate between Iframe pages

2. Understand the Window.postMessage API

3. Complete a small demo of Iframe communication

Open source Iframe communication framework

This is my internal source Iframe communication framework open source, convenient for everyone to use the warehouse address: github.com/HaiyaoTec/w… If it is helpful to you, please give a little star🌟 encouragement

Why Iframe communication ❓

  • Sometimes we need to combine two separate projects, and Iframe is needed for some simple data communication
  • For example, the chat room is embedded with Web applications
  • For example, something like a micro front end, which also needs to communicate between projects, although the micro front end does not do this, but in a similar way, we all need to figure out how to communicate between two independent projects

How do I communicate with Iframe?

  • Leveraging the powerful apis provided by browsers,window.postMessageYou can do that!

Window. PostMessage explanation

The * window.postmessage ()* method can safely implement cross-source communication. In general, scripts with two different pages can only communicate with each other if the page executing them is on the same protocol (usually HTTPS), port number (443 is the default value for HTTPS), and host (the module document.domain of the two pages is set to the same value). The * window.postmessage ()* method provides a controlled mechanism to circumvent this limitation and is safe as long as it is used correctly.

In broad terms, a window can get a reference to another window (such as targetWindow = window.opener) and then distribute a MessageEvent message by calling the targetwindow.postMessage () method on the window. The window receiving the message is free to process this event (en-US) as needed. Arguments passed to window.postMessage(), such as message, are exposed to the window receiving the message through the message event object.

grammar

otherWindow.postMessage(message, targetOrigin, [transfer]);
Copy the code

otherWindow

A reference to another window, such as the contentWindow property of iframe, the window object returned by executing window.open, or the window.frames named or numeric index.

message

Data to be sent to other Windows. It will be serialized by a structured cloning algorithm. This means you can safely pass data objects to the target window without having to serialize them yourself. [1]

targetOrigin

The origin property of a window specifies which window can receive message events, either as a string “*” (for unrestricted) or as a URI. If any of the protocol, host address, or port of the target window does not match the value provided by targetOrigin, the message will not be sent. A message will only be sent if all three match. This mechanism controls which Windows messages can be sent to; For example, this parameter is especially important when a password is sent using postMessage, and its value must be exactly the same as the Origin property of the intended recipient of the message containing the password to prevent the password from being intercepted by a malicious third party. If you know exactly which window the message should be sent to, always provide a targetOrigin with the exact value, not *. Not providing an exact target will result in data being leaked to any malicious site interested in the data.

Transfer the optional

Is a string of Transferable objects that are passed along with Message. Ownership of these objects is transferred to the receiver of the message, and ownership is no longer retained by the sender.

To summarize in plain English:

  • OtherWindow is the page that you want to receive the message from, and you use that page’s window to send the message
  • Message is the data you want to send
  • TargetOrigin is usually the source of otherWindow. The protocol + domain + port must be the same in order to receive the message
  • Transfer is generally ignored

Demo

First, to explain:

  • A->B sends the message

  • Popup is another window in which your current window repops

  • You want to send a message to PopUp

  • Event. source indicates which Window sent the message (Window)

A

/* * The domain name of window A is 
      
       . The following is the code under the script tag of window A: */
      

var popup = window.open(... popup details...) ;// If the popup is not blocked and the load is complete

// This line does not send a message, even assuming that the current page has not changed location (because the targetOrigin is not set correctly)
popup.postMessage("The user is 'bob' and the password is 'secret'"."https://secure.example.net");

// Assuming the current page does not change location, this statement will successfully add message to the send queue (targetOrigin is set correctly)
popup.postMessage("hello there!"."http://example.org");

function receiveMessage(event)
{
  Can we trust the sender of the message? (Maybe this sender is not the same page we originally opened).
  if(event.origin ! = ="http://example.org")
    return;

  // Event. source is the popup page we open with window.open
  // event.data is the message popup sends to the current page "Hi there yourself! the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);

Copy the code

B

The popup domain name is 
      
       . Here is the code in the script tag: */
      

// This function is called by addEventListener when A page postMessage is called
function receiveMessage(event)
{
  // Can we trust the source of information?
  if(event.origin ! = ="http://example.com:8080")
    return;

  // event.source is the source of the current pop-up page
  // event.data is "Hello there!"

  // Assuming you have verified the origin of the received information (which you should do at any time), a convenient way to do this is to add event.source
  // as the reply object, and the event. Origin as the targetOrigin
  event.source.postMessage("hi there yourself! the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);

Copy the code

Pay attention to

Not checking origin and Source can lead to cross-site scripting attacks

Any window can access this method in any other window and send a message to it at any time, regardless of the document’s location in the window. Therefore, any event listener used to receive a message must first check the identity of the sender of the message using the Origin and source properties. This should not be underestimated: failure to check origin and source properties can lead to cross-site scripting attacks.

As with any asynchronously scheduled script (timeout, user-generated events), it is impossible for a postMessage caller to detect when an event handler that listens for events sent by postMessage throws an exception.

The value of the Origin property for the dispatch event is not affected by the current value of document.domain in the calling window.

For IDN host names only, the origin attribute is not always Unicode or Punycode; When using this property, check IDN and Punycode values for maximum compatibility if you expect messages from IDN web sites. This value will always end up being IDN, but for now you should work with both IDN and Punycode forms.

When the send window contains javascript: or data: URL, the value of the Origin property is for the script that loaded the URL

Reference πŸ“š

  • MDN

Conclusion 🌞

My Iframe communication guide 🧭 then this article will be over, actually very simple, the purpose of the article is about the summary of the daily work and output, output some feel useful things for people, food is not food is not important, but love πŸ”₯, hope everyone can like my articles, I am really very attentively in writing, also hope that through articles meet more like-minded friends, If you also like to toss, welcome to add my friends, sand sculpture, progress together.

Making πŸ€– : sudongyu

Personal blog πŸ‘¨πŸ’»: Frozen fish blog

Vx πŸ‘¦ : sudongyuer

Write in the last

Guys, if you like my words, give 🐟🐟 a thumbs up πŸ‘ or follow βž• to support me the most.

Add me on wechat: Sudongyuer, invite you into the group and learning the front together, become a better engineer ~ (group of qr code here – > front to go to bed early, qr code has expired, see the links to the boiling point in the comments, I will put the latest qr code in the comments section, of course, can also add me WeChat I pull you into the group, after all, I also am interesting front end, I also not bad 🌟 ~