当前位置:网站首页>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
terminatedIn the state of , Will release all resources . in other words , hereAsynchronous threadContext 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 :
边栏推荐
- Challenges faced by virtual human industry
- [the 2023 autumn recruitment of MIHA tour] open [the only exclusive internal push code of school recruitment eytuc]
- Energy momentum: how to achieve carbon neutralization in the power industry?
- 业务太忙,真的是没时间搞自动化理由吗?
- md5工具类
- The sandbox has reached a cooperation with digital Hollywood to accelerate the economic development of creators through human resource development
- 虚拟人产业面临的挑战
- More than 30 institutions jointly launched the digital collection industry initiative. How will it move forward in the future?
- SPSS安装激活教程(包含网盘链接)
- Microservices -- Opening
猜你喜欢

Nat. Commun.| Machine learning jointly optimizes the affinity and specificity of mutagenic therapeutic antibodies

Redis的持久化机制

Logo special training camp section III initial creative techniques

Introduction and application of bigfilter global transaction anti duplication component

2022-07-04:以下go语言代码输出什么?A:true;B:false;C:编译错误。 package main import “fmt“ func main() { fmt.Pri

The sandbox has reached a cooperation with digital Hollywood to accelerate the economic development of creators through human resource development

Domestic database chaos

攻防世界 MISC 进阶区 Ditf

The Sandbox 和数字好莱坞达成合作,通过人力资源开发加速创作者经济的发展

嵌入式开发:技巧和窍门——提高嵌入式软件代码质量的7个技巧
随机推荐
Recommendation of mobile app for making barcode
Scala download and configuration
达梦数据凭什么被称为国产数据库“第一股”?
UML diagram memory skills
PHP short video source code, thumb animation will float when you like it
虚拟人产业面临的挑战
MySQL storage data encryption
Force buckle 2_ 1480. Dynamic sum of one-dimensional array
Common open source codeless testing tools
md5工具类
攻防世界 MISC 进阶区 hong
Nat. Commun.| Machine learning jointly optimizes the affinity and specificity of mutagenic therapeutic antibodies
Logo special training camp Section V font structure and common design techniques
攻防世界 MISC 高手进阶区 001 normal_png
【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
LOGO特训营 第五节 字体结构与设计常用技法
Unity-VScode-Emmylua配置报错解决
The sandbox has reached a cooperation with digital Hollywood to accelerate the economic development of creators through human resource development
Introducing QA into the software development lifecycle is the best practice that engineers should follow
不同环境相同配置项的内容如何diff差异?