当前位置:网站首页>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
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 :
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 .
边栏推荐
- Volcano resource reservation feature
- Technology blog learning website
- Ros2 topic (VIII)
- 睿智的目标检测59——Pytorch Focal loss详解与在YoloV4当中的实现
- Orin 安装CUDA环境
- Technical conference arrangement
- Edge calculation data sorting
- Interpretation of the earliest sketches - image translation work sketchygan
- Utf8 encoding
- Orin 两种刷机方式
猜你喜欢
程序中的负数存储及类型转换
PHY drive commissioning - phy controller drive (II)
Vant weapp swippecell set multiple buttons
ROS2——初识ROS2(一)
ROS2——Service服务(九)
Inftnews | drink tea and send virtual stocks? Analysis of Naixue's tea "coin issuance"
Mipi interface, DVP interface and CSI interface of camera
Get class files and attributes by reflection
ROS2——配置开发环境(五)
1290_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
随机推荐
IPage can display data normally, but total is always equal to 0
网易To B,柔外刚中
Dameng database all
【软件测试】02 -- 软件缺陷管理
ROS2——功能包(六)
使用paping工具进行tcp端口连通性检测
Preemption of CFS scheduling
docker安装mysql并使用navicat连接
Mid 2022 documentary -- the experience of an ordinary person
Marvell 88E1515 PHY loopback模式测试
Ros2 - install ros2 (III)
PHY驱动调试之 --- MDIO/MDC接口22号和45号条款(一)
Binary search (half search)
Concurrent programming - how to interrupt / stop a running thread?
现在有html文件,和用vs制作的mvc(连接了数据库),怎么两个相连?
Log4qt usage of logbase in QT project
testing framework
Mipi interface, DVP interface and CSI interface of camera
Vant Weapp SwipeCell設置多個按鈕
new和malloc的区别