当前位置:网站首页>"Demand optimization" uses PostMessage to solve the cross domain problem of localstorage
"Demand optimization" uses PostMessage to solve the cross domain problem of localstorage
2022-07-22 16:12:00 【Front end non release Leo】
background
earlier , There's a need in the project : Other platforms need to carry data to jump to our platform , And automatically open the pop-up window and render the carried data .
My initial plan was localStorage, Before other platforms jump over , Store data localStorage, Jump to our platform , I'll judge first localStorage Is there a specified “ key ”( It is required to deposit localStorage Medium “ key ” Be special and unique ), If there is , I will take out the data for processing and open the pop-up window to render the number .
// Save the data before jumping to other platforms localStorage
localStorage.setItem("popDataList",JSON.stringify(data))
// Jump to our platform , from localStorage Take out the data
let popDataList = JSON.parse(localStorage.getItem("popDataList"))
if(popDataList){
// If it exists, process it and open the pop-up window to render data
}
// Close the pop-up window , Clear cache , Avoid affecting the normal function of the page
localStorage.removeItem("popDataList")
When conducting joint commissioning with other platforms at first , Deo gratias . But there is a problem these two days : When conducting joint commissioning with a platform , It is found that the data is stored in localStorage, But after jumping to our platform localStorage There's no data , That is, the deposit failed . After locating, we found that the domain name of their platform is different from ours , That is, cross domain , and localStorage Cross domain is not supported , Therefore, our platform has no corresponding localStorage. The reason why it was successful before , Because the platform domain name of the joint commissioning is the same , For different domain names, this scheme is not applicable .
Optimize
What do I do ? Only secondary optimization can be carried out . Obviously , We need to choose a scheme that supports cross domain , therefore , I chose postMessage.
postMessage() For secure cross source communication .
Send a message
The syntax is as follows :
otherWindow.postMessage(message, targetOrigin, [transfer]);
Parameters | explain |
---|---|
otherWindow | A reference to another window , such as iframe Of contentWindow attribute 、 perform window.open Window object returned 、 Or named or indexed window.frames. |
message | Will be sent to others window The data of . |
targetOrigin | Specify which windows can receive message events , The value could be *( Means unlimited ) Or a URI. |
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 . |
receive messages
The receiver has an event listener , monitor "message" event , At the same time, we can also verify the source address , To ensure that it is a trusted sending address .
window.addEventListener('message', function (e) { // monitor message event
if (e.origin !== "https://www.myTest.com") { // Verify message source address
return;
}
// Take out the data
console.log(e.data)
});
Secondary optimization of the project
The following simulates a real project scenario
Other platforms :http://localhost:8080
Our platform :http://localhost:8081
Other platforms pass data before jumping postMessage Send out
window.open("http://localhost:8081")
window.postMessage("postMessage send data !","http://localhost:8081")
Our platform monitors on the designated page , get data
window.addEventListener("message",function(e){
console.log(e,'123')
alert(e.data)
})
When I thought No problem, There's another problem , When I jumped from other platforms to our platform , The effect is as follows :
The console prints as follows :
Obviously , Sending failed ,data Follow origin It's not true . So I figured it out , Try modifying the code
let popWindow = window.open("http://localhost:8081")
popWindow.postMessage("postMessage send data !","http://localhost:8081")
To verify again , The result is the same as above , I'm curious , Why is that? ? The receiver did not listen to the specified message.
I was thinking , Is it possible that we are using postMessage Page Jump while sending data , The newly opened page has not been monitored at this time , So I can't monitor , And when we set up monitoring ,postMessage The action has expired .
So I try to modify the code of sending data , Add the timer to delay sending
let popWindow = window.open("http://localhost:8081")
setTimeout(() => {
popWindow.postMessage("postMessage send data !","http://localhost:8081")
},1000)
Try again , Something interesting happened , The prompt box appears twice .
The first result is still consistent with the above , The prompt and printing are incorrect
But I got the data sent for the second time
Console printing ,data Follow origin It's all right
Adding a timer can solve the problem of sending data and opening a new page to get data at the same time , Also verified my guess .
Come here , Our problem has been basically solved , The requirements are basically completed , Of course, it can be further optimized , For example, verify the message source address , To ensure that it is a trusted sending address
window.addEventListener("message",function(e){
if(e.origin !== "http://localhost:8080"){
return
}
console.log(e,'123')
alert(e.data)
})
Above optimization , It can ensure that the source is credible , At the same time, unnecessary treatment is reduced , Such as error prompt box after optimization
It won't pop up again , Because judging from the error printing information above , its origin We didn't specify , That is, the source is not credible .
Of course , You can also reduce the timer extension time when sending messages , Reduce user wait time , Ensure a good experience
let popWindow = window.open("http://localhost:8081")
setTimeout(() => {
popWindow.postMessage("postMessage send data !","http://localhost:8081")
},200)
After the above optimization , The demand goal is achieved , Good user experience , bernays .
The complete code is attached ( It's simple )
The sender
let popWindow = window.open("http://localhost:8081")
setTimeout(() => {
popWindow.postMessage("postMessage send data !","http://localhost:8081")
},200)
// Be careful : A timer must be used , If the data sent is an object type , You can use it first JSON.stringify() serialize
The receiver
window.addEventListener("message",function(e){
if(e.origin !== "http://localhost:8080"){ // Verify that the source is trusted
return;
}
console.log(e.data)
// Be careful : If e.data yes JSON.stringify() Serialized data , Need to use JSON.parse() To restore
// Follow up operation ...
})
边栏推荐
- Why does the system we developed have concurrent bugs? What is the root cause of concurrent bugs?
- Ssti Summary and ciscn 2019 South East China] double secret
- [learn rust together] rust preparation before learning -- Annotation and formatted output
- Is it safe to open an account on the access letter?
- What are the common probe set and gallery set
- QT notes - customized qlistwidget
- PPy HSA conductive polymer polypyrrole PPy material BSA white rice nanoparticles / albumin coated nano lipid carrier BSA NLC
- Ros2 self study notes: TF coordinate management
- Word: insert vector diagram with specified color
- QT notes - a brief introduction to qtimer and qtimerevent
猜你喜欢
DOM之浏览器渲染流程 和重绘 回流
[code Notes] - u-net
ENVI_ Idl: batch production of thematic maps
白蛋白索拉非尼/Gd2O3/CuS复合白蛋白纳米粒/ALB-ICG-DOX白蛋白纳米粒包ICG&DOX的制备
NB-IOT可以应用在哪些领域
载胶原蛋白酶的白蛋白复合纳米颗粒/牛血清白蛋白包裹二氧化铈纳米人工酶
Monopoly of Web3 social protocol and soul binding token
机器学习基础篇(5)图像轮廓
QT notes - customized qlistwidget
Don't look for it, it's all sorted out for you -- complete collection of SQL statements
随机推荐
The big problem of HA automatic failover (active) namenode
Summary of product related issues (Part 1)
Preloading and lazy loading of DOM
P6327 interval plus interval sin sum
Beijing, Shanghai, Guangzhou, Shenzhen and Hangzhou 30K test question: how to allocate JVM memory model?
Online RPC timeout troubleshooting and subsequent GC tuning ideas
PXE网络装机
腾讯计划关停数字藏品业务“幻核”(7月21日)
NB-IOT可以应用在哪些领域
The principle of distributed transaction is simple, and it is full of holes
Segment tree learning record
[elaborate] ES6's array expansion method, object expansion method, string expansion method Object level depth
DOM之style的操作
Linux environment
m利用SIMILINK仿真模块实现多径信道的动态仿真模拟
命令行程序测试自动化
Bovine serum albumin platinum composite nanomaterials /hsa PC NPs human serum albumin (HSA) coated phthalocyanine nanoparticles
【leetcode】
对接三方支付接口需要满足哪些需求?
傍晚的天空