当前位置:网站首页>Iframe usage and contentwindow, parent and PostMessage communication methods
Iframe usage and contentwindow, parent and PostMessage communication methods
2022-06-26 12:26:00 【C+ Ankou wood】
problem :
How to communicate messages ( Parent to child , The child receives messages from the parent , You can also call a child's method directly from the parent ; Son to father , The parent receives messages from the child ;)
How to find the specified child or parent window( If iframe Too many levels ), And how to send messages without affecting others message monitor
One 、iframe Use
<iframe style={
{
border:0,width:"100%",height:630,}} src={
src} />
- How to communicate messages ( Parent to child , The child receives messages from the parent ; Son to father , The parent receives messages from the child )
Method 1 : Directly by getting a parent or child window To operate ( Limit : Must be in the same domain )
// Method of parent calling child :
this.iframe.contentWindow.iframe Properties of / Method
// or
document.getElementById("myIframe").contentWindow.iframe Properties of / Method
// The child calls the parent method : adopt parent Get the parent directly window
parent.document. Properties of / Method
Method 2 : adopt postMessage communicate ( Limit : Father son agreement is required )
// The parent listens to the child messages :
window.addEventListener('message',function(event){
...
})
// The child sends a message to the parent : It can be done by window The corresponding parent is found for the attribute of ( there parent Represents the parent of the immediate parent )
// Nest one layer to use window.top(parent), Multi-storey window.frameElement,
// Use top instead of window,top Point to iframe Topmost window
window.top.postMessage(msg,' Parent window source ');
parent.postMessage(data, "*");
// Father sends message to son
document.getElementById("iframe").contentWindow.postMessage(msg,' Child window source ')
iFrame.onload = function(){
//iframe Send a message immediately after loading
iFrame.contentWindow.postMessage({
msg: 'MessageFromIndexPage'},'*');
}
// The child listens to the parent's message
window.addEventListener("message", (e) => this.listenFunc(e));
- How to find the specified child or parent window( If iframe Too many levels ), And how to send messages without affecting others message monitor
while(true) {
// Judge , Find the parent you are looking for window, This can be done by window Binding properties on the
if(currentWindow.isParent = true) {
currentWindow.postMessage(data, "*")
}
if(currentWindow == window.top) {
break; // Prevent a dead cycle
} else {
currentWindow = currentWindwo.parent;
}
}
- origin Usefulness
event.origin You can get the source path of the current message , By judging the present iframe Of url, Determine whether it is the message source of the specified page
Two 、React Native Of WebView Communication with sub content
// RN Of WebView
<WebView
ref={
ref => this.webview = ref}
source={
{
uri: ...}}
javaScriptEnabled={
true}
onMessage={
this.handleMassage}
allowFileAccess={
true}
onLoadStart={
}
onLoadEnd={
}
/>
- Listening to receive web( Son ) Message sent
// receive web Message sent
handleMessage(event) {
const data = JSON.parse(event.nativeEvent.data);
const code = data.code;
const msg = data.msg;
switch(code) {
case 0:
console.log(msg);
break;
}
}
- web( Son ) Send a message to react native
// web Send a message to react native
const data = {
code: code, msg: msg};
window.ReactNativeWebView.postMessage(JSON.stringify(data));
- React Native( Father ) Send a message to web( Son )
// Send a message to web
sendMessageToWebView(code, msg) {
const data = {
code: code, msg: msg};
if(this.webview) {
this.webview.postMessage(JSON.stringify(data));
} else {
console.log("no webview ref")
}
}
- web( Son ) Yes React Native( Father ) Monitoring of news
// web monitor react native Of postMessage news , There has to be document, Otherwise, no message will be heard
window.document.addEventListener("message", this.onMessageListener.bind(this));
onMessageListener(event) {
const data = JSON.parse(event.data);
const code = data.code;
const msg = data.msg;
switch(code) {
case ...
}
}
3、 ... and 、 android Of webview And communications containing content ( Just a brief introduction )
agentWeb be relative to webview Use
android The current... Can be defined in window Under the name ,
web have access to similar window.WebAppInterface.onPostMessage(JSON.stringify(data)) To send a message ,WebAppInterface Need to be in Android In the definition of
Sum up :
web Of iframe Between ,web and RN Of webview Between ,web and android Communication between , Is to use message To monitor , Need to pay attention to the source , Otherwise, if there are multiple messages of the same type but different types , It is easy to cause conflict and confusion of monitoring
For message sending , The three types are different , However, it is necessary to distinguish between multiple types of the same type , Otherwise, there is still the problem of conflict and confusion
边栏推荐
- 24 database interview questions that must be mastered!
- 我想知道同花顺是炒股的么?在线开户安全么?
- Jmeter响应时间和tps监听器使用教程
- VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」
- Question B of 2016 Sichuan Ti Cup Electronic Design Competition
- 【毕业季·进击的技术er】忆毕业一年有感
- Analysis report on dynamic research and investment planning suggestions of China's laser medical market in 2022
- Investment planning and forecast report on the future direction of China's smart agriculture during the 14th five year plan (2022)
- dried food! Yiwen will show you SD card, TF card and SIM card!
- 房租是由什么决定的
猜你喜欢

Pratique de l'attaque et de la défense du réseau HUST | 6 Expérience de sécurité du microprogramme de l'équipement IOT | expérience 2 technologie d'atténuation des attaques de l'équipement IOT basée s

Jmeter响应时间和tps监听器使用教程

MySQL optimization - index (what is an index?)

1、 MySQL introduction

Realize microservice load balancing (ribbon)
![Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding](/img/58/2a56c5c9165295c830082f8b05dd98.png)
Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding

2021 q3-q4 investigation report on the use status of kotlin multiplatform

ctfshow web入门 命令执行web75-77
![[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test](/img/2f/f44381ea759f4c1c957a8f9434f0ee.png)
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test

dried food! Yiwen will show you SD card, TF card and SIM card!
随机推荐
Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding
Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
Five strategies and suggestions of member marketing in consumer goods industry
How long ago did PHP get
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
Thinkphp5 query report: sqlstate[hy093]: invalid parameter number
The best CMDB system
JMeter response time and TPS listener tutorial
[graduation season · advanced technology Er] I remember the year after graduation
MOS管基本原理,单片机重要知识点
Spark-day03-core programming RDD operator
PHP returns false when calling redis method decrby less than 0
Five trends of member management in 2022
Jsonarray and jsonobject of fastjson [easy to understand]
【毕业季·进击的技术er】忆毕业一年有感
我想知道同花顺是炒股的么?在线开户安全么?
2022 China smart bathroom cabinet Market Research and investment Competitiveness Analysis Report
dried food! Yiwen will show you SD card, TF card and SIM card!
One click deployment of your own community forum
11、 Box styles and user interface