当前位置:网站首页>How to send a reliable request before closing the page
How to send a reliable request before closing the page
2022-07-04 22:38:00 【swlws9527】
One 、 problem
from A Page goes to B Before page , Send a message to the background /log
request , How to ensure that this request will be received and processed .
Scene: the repetition
function nextPage() {
fetch("/log", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
some: "data",
}),
});
window.location.href = "/other.html";
}
In this code , After successful page switching , The background cannot receive /log
Requested . reason :
- js The implementation of can be divided into
The main thread
、Asynchronous thread
- When the page enters
terminated
In the state of , Will release all resources . in other words , hereAsynchronous thread
Context not executed in , Will no longer be dealt with .
Two 、 Solution
2.1 async/await
Since the request is executed because of asynchrony , Then change to synchronization .
async function nextPage() {
await fetch("/log", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
some: "data",
}),
});
window.location.href = "/other.html";
}
This method will block code execution
2.2 keepAlive
fetch
Set in keepalive
by true
when , Even if the page that initiated the request is terminated
state , Will also remain connected . Use this feature , You can send reliable requests .
function nextPage() {
fetch("/log", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
some: "data",
}),
keepalive: true,
});
window.location.href = "/other.html";
}
2.3 navigator.sendBeacon
Use sendBeacon()
The method allows users to send data asynchronously to the proxy server , At the same time, it will not delay the unloading of the page or affect the loading performance of the next navigation , It means :
- Data transmission is reliable .
- Data asynchronous transmission .
- It does not affect the loading of the next navigation .
Code example :
function nextPage() {
navigator.sendBeacon(
"/log",
JSON.stringify({
some: "data",
})
);
window.location.href = "/other.html";
}
sendBeacon()
API Adding request headers is not supported , You can use Blob
Make some changes to support the request header
function nextPage() {
const blob = new Blob([JSON.stringify({
some: "data" })], {
type: "application/json; charset=UTF-8",
});
navigator.sendBeacon("/log", blob);
window.location.href = "/other.html";
}
It should be noted that , stay Chrome
Of network
Under the panel , Its document type is ping
, It's not common fetch、xhr
type .
2.4 <a>
Labeled ping attribute
More and more manufacturers support ping
The attribute is . Example :
<a href="/other.html" ping="/log">other page</a>
Click on a
When labeling , An additional request will be sent /log
, Its request header contains several special values :
{
"ping-from": "http://127.0.0.1:3000/",
"ping-to": "http://127.0.0.1:3000/other.html",
"content-type": "text/ping"
}
3、 ... and 、 Options
If , have access to fetch()+keepalive:
- You need to customize the request header .
- Use GET request , No POST request .
- Support older browsers ( Such as IE), And it has been loaded fetch polyfill.
But if the following conditions are met ,sendBeacon() Maybe a better choice :
- Make a simple service request , Don't need too much customization .
- Prefer cleaner 、 More elegant API.
- We want to ensure that your request does not compete with other high priority requests sent in the application .
Reference resources :
边栏推荐
- Jvm-Sandbox-Repeater的部署
- 集群的概述与定义,一看就会
- 高中物理:直线运动
- Flask 上下文详解
- 串口数据帧
- Interview essential leetcode linked list algorithm question summary, whole process dry goods!
- 业务太忙,真的是没时间搞自动化理由吗?
- How diff are the contents of the same configuration item in different environments?
- 攻防世界 MISC 进阶 glance-50
- [acwing] solution of the 58th weekly match
猜你喜欢
达梦数据凭什么被称为国产数据库“第一股”?
LOGO special training camp section I identification logo and Logo Design Ideas
NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse
Tiktok actual combat ~ the number of comments is updated synchronously
PMO: compare the sample efficiency of 25 molecular optimization methods
攻防世界 MISC 进阶区 hong
UML图记忆技巧
The Sandbox 和数字好莱坞达成合作,通过人力资源开发加速创作者经济的发展
Unity-VScode-Emmylua配置报错解决
It is said that software testing is very simple, but why are there so many dissuasions?
随机推荐
质量体系建设之路的分分合合
Unity修仙手游 | lua动态滑动功能(3种源码具体实现)
odps 中 对表进行了一次备份,为什么在元数据库查m_table 时,两张表的逻辑大小不一致,但数
leetcode 72. Edit Distance 编辑距离(中等)
Interview essential leetcode linked list algorithm question summary, whole process dry goods!
Force buckle 2_ 1480. Dynamic sum of one-dimensional array
Service online governance
傳智教育|如何轉行互聯網高薪崗比特之一的軟件測試?(附軟件測試學習路線圖)
leetcode 72. Edit distance edit distance (medium)
Common shortcut keys for hbuilder x
Lost in the lock world of MySQL
Locust performance test - environment construction and use
How to manage 15million employees easily?
蓝队攻防演练中的三段作战
醒悟的日子,我是怎么一步一步走向软件测试的道路
Deployment of JVM sandbox repeater
Ascendex launched Walken (WLKN) - an excellent and leading "walk to earn" game
LOGO特训营 第一节 鉴别Logo与Logo设计思路
好用app推荐:扫描二维码、扫描条形码并查看历史
PMO: compare the sample efficiency of 25 molecular optimization methods