当前位置:网站首页>PostMessage communication

PostMessage communication

2022-07-05 07:07:00 Black cat crimson

In the business , One form of development is : Multiple subsystems are integrated into a parent system . Each system manages different business and logic , They do not interfere with each other .

that , How can we operate the content in the subsystem in the parent system page ?

First, through vite Initialize two items .

The parent system port number is 3001, The subsystem port number is 3000.

 Insert picture description here

Then in the parent system page, a iframe label , Open the subsystem page :

<div class="iframe" v-if="show">
	<iframe 
    	:src="`http://localhost:3001/#/?picUrl=${picUrl}`" 
		frameborder="0"
		style="width:100%;height:100%"
    >
    </iframe>
</div>

You can see in the parent system page , Successfully opened the subsystem page content .

 Insert picture description here

postmessage signal communication

stay web Project approval iframe Embed another third party web project , The third party web Click a button in the project to call in real time web The global function of the project opens a global pop-up window or performs route jump , At this time, there is data interaction between the two projects , Obviously, it violates the homology strategy , stay HTML5 Standard introduced window Under the object postMessage Method , Scripts from different sources can be allowed to communicate asynchronously with Limited , Cross-text files can be implemented 、 Many window 、 Cross-domain messaging .

window.postMessage() Method can realize cross source communication safely . Usually , For two different page scripts , Only if the pages that execute them are in the same protocol ( Usually it is https), Port number (443 by https The default value of ), And host ( Module of two pages Document.domain Set to the same value ) when , These two scripts can communicate with each other .window.postMessage() Method provides a controlled mechanism to circumvent this limitation .

In a broad sense , One window can get a reference to another window ( such as targetWindow = window.opener), Then call... On the window targetWindow.postMessage() Method to distribute a MessageEvent news . The window for receiving messages can be opened freely as needed Handle this event (en-US). Pass to window.postMessage() Parameters of ( such as message ) take The message event object is exposed to the window that receives the message .

grammar

otherWindow.postMessage(message, targetOrigin, [transfer]);
  • Parameters
    • otherWindow: A reference to another window , such as iframe Of contentWindow attribute 、 perform window.open Window object returned .
    • message: Will be sent to others window The data of . It will be Structured cloning algorithm serialize . This means that you can safely transfer data objects to the target window without any restrictions on serialization .
    • targetOrigin: windowed origin Property to specify which Windows can receive message events , The value can be a string "*"( Means unlimited ) Or a URI. When sending a message , If the target window of the protocol 、 The host address or port does not match any of the three targetOrigin Provide the value of the , Then the message will not be sent ; Only three of them match perfectly , The message is sent . This mechanism is used to control which windows messages can be sent to .
    • transfer( Optional ): It is a list of and message Simultaneous transitive Transferable object . Ownership of these objects is transferred to the recipient of the message , The sender will no longer retain ownership .

It is easy to use

First look at it. 3001 Port page , Look at how he told caller 3000 The port page sends information .

localhost:3001

<template>
<div>
   A page of the subsystem 
  <div @click="toFather" class="btn"> Operate the data in the parent system </div>
</div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
    const toFather = () => {
      //  call postMessage Method , The first parameter is the data to be transferred , The second parameter is  origin  Source data 
      parent.postMessage({msg: " Black cat several crimson "}, "*")
    }
</script>

there parent It looks a bit abrupt , Get into lib.dom.d.ts Look at his definition under the document :

/** Refers to either the parent WindowProxy, or itself. It can rarely be null e.g. for contentWindow of an iframe that is already removed from the parent. */
declare var parent: WindowProxy;
/** 

You can see parent Here is a Window Proxy object of , This sentence can also be written as :

window.parent.postMessage({
    msg: " Black cat several crimson "}, "*")

localhost:3000

Let's take a look at how the caller page receives messages :

<script setup>
  import {ref, onMounted} from 'vue'

  const receiveMessage = (event) => {
    console.log(event.data.msg); //  Black cat several crimson 
  }
  onMounted(()=>{
    window.addEventListener('message',receiveMessage, false)
  })
</script>

  • When the page is mounted , adopt addEventListener monitor message event
  • The specific monitoring method will receive a event Object parameters , It can receive the data from the callee page

This is the basic idea , Now look at the final effect in the page :

 Insert picture description here

Expand

origin Judge

If you don't want to receive from other websites message, Don't do it message Event add any event listener . It's a completely safe way to avoid security issues .

You can see in the picture above , The message object contains origin Data to store source information , Therefore, we can judge the source according to it , After all, you can't monitor the information sent by those malicious websites .

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

function receiveMessage(event) {
    
  let origin = event.origin || event.originalEvent.origin;
  //  If not 3001 Messages delivered from the port page , The caller does not process these messages 
  if (origin !== "http://localhost:3001")
    return;
  // ...
}

Be careful : This origin There is no guarantee that this window is current or future origin, because postMessage May be navigated to a different location after being called .

If you really want to receive from another website message, please Always use a origin and source Property to verify the identity of the sender . Any window can send messages to any other window , And the page cannot guarantee that unknown senders will not send malicious messages .

Even after authentication , It should still be Always verify the syntax of received messages . otherwise , A security vulnerability in a website that only sends trusted messages may open a cross site scripting vulnerability in the website .

原网站

版权声明
本文为[Black cat crimson]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050638004027.html