当前位置:网站首页>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.

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 .

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
Transferableobject . 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
addEventListenermonitor 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 :

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 .
边栏推荐
- Steps and FAQs of connecting windows Navicat to Alibaba cloud server MySQL
- 2022.06.27_每日一题
- An article was opened to test the real situation of outsourcing companies
- Special training of C language array
- Page type
- Unity UGUI不同的UI面板或者UI之间如何进行坐标匹配和变换
- 6-3 find the table length of the linked table
- Netease to B, soft outside, hard in
- Skywalking全部
- 三体目标管理笔记
猜你喜欢

Volcano 资源预留特性

ROS2——初识ROS2(一)

一文揭开,测试外包公司的真实情况

Logical structure and physical structure

An article was opened to test the real situation of outsourcing companies

MySQL (UDF authorization)

Rehabilitation type force deduction brush question notes D1

Skywalking all

PHY drive commissioning - phy controller drive (II)

1290_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
随机推荐
Lexin interview process
How to answer when you encounter a jet on CSDN?
Preemption of CFS scheduling
并发编程 — 死锁排查及处理
SOC_SD_CMD_FSM
vim
Ros2 - function package (VI)
Technical conference arrangement
All English in the code
睿智的目标检测59——Pytorch Focal loss详解与在YoloV4当中的实现
Cookie、Session、JWT、token四者间的区别与联系
【MySQL8.0不支持表名大写-对应方案】
docker安装mysql并使用navicat连接
The differences and connections among cookies, sessions, JWT, and tokens
Rehabilitation type force deduction brush question notes D3
About vscode, "code unreachable" will be displayed when calling sendline series functions with pwntools“
解读最早的草图-图像翻译工作SketchyGAN
Sre core system understanding
现在有html文件,和用vs制作的mvc(连接了数据库),怎么两个相连?
MySQL setting trigger problem