当前位置:网站首页>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 :
边栏推荐
- 集群的概述与定义,一看就会
- leetcode 72. Edit Distance 编辑距离(中等)
- odps 中 对表进行了一次备份,为什么在元数据库查m_table 时,两张表的逻辑大小不一致,但数
- SPSS installation and activation tutorial (including network disk link)
- Embedded development: skills and tricks -- seven skills to improve the quality of embedded software code
- Li Kou 98: verify binary search tree
- UML diagram memory skills
- Locust性能测试 —— 环境搭建及使用
- Ascendex launched Walken (WLKN) - an excellent and leading "walk to earn" game
- 新版判断PC和手机端代码,手机端跳转手机端,PC跳转PC端最新有效代码
猜你喜欢
LOGO特訓營 第三節 首字母創意手法
How to transfer to software testing, one of the high paying jobs in the Internet? (software testing learning roadmap attached)
More than 30 institutions jointly launched the digital collection industry initiative. How will it move forward in the future?
Close system call analysis - Performance Optimization
Embedded development: skills and tricks -- seven skills to improve the quality of embedded software code
共创软硬件协同生态:Graphcore IPU与百度飞桨的“联合提交”亮相MLPerf
Logo Camp d'entraînement section 3 techniques créatives initiales
Why is Dameng data called the "first share" of domestic databases?
UML diagram memory skills
虚拟人产业面临的挑战
随机推荐
md5工具类
Ascendex launched Walken (WLKN) - an excellent and leading "walk to earn" game
Taobao commodity review API interface (item_review get Taobao commodity review API interface), tmall commodity review API interface
Locust性能测试 —— 环境搭建及使用
leetcode 72. Edit distance edit distance (medium)
集群的概述与定义,一看就会
The proofreading activity of data science on the command line second edition was restarted
sobel过滤器
PHP short video source code, thumb animation will float when you like it
串口数据帧
国产数据库乱象
LOGO特训营 第二节 文字与图形的搭配关系
BigFilter全局交易防重组件的介绍与应用
php短视频源码,点赞时会有大拇指动画飘起
特征缩放 标准化 归一化
2022-07-04: what is the output of the following go language code? A:true; B:false; C: Compilation error. package main import “fmt“ func main() { fmt.Pri
Close system call analysis - Performance Optimization
Redis sentinel simply looks at the trade-offs between distributed high availability and consistency
Nat. Commun.| Machine learning jointly optimizes the affinity and specificity of mutagenic therapeutic antibodies
Logo special training camp Section IV importance of font design