当前位置:网站首页>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 :
边栏推荐
- 攻防世界 misc 高手进阶区 a_good_idea
- Energy momentum: how to achieve carbon neutralization in the power industry?
- Huawei Nova 10 series released Huawei application market to build a solid application security firewall
- Nat. Commun.| Machine learning jointly optimizes the affinity and specificity of mutagenic therapeutic antibodies
- 制作条形码的手机App推荐
- With this PDF, we finally got offers from eight major manufacturers, including Alibaba, bytek and Baidu
- Force buckle 3_ 383. Ransom letter
- Unity-VScode-Emmylua配置报错解决
- Google Earth Engine(GEE)——Tasks升级,实现RUN ALL可以一键下载任务类型中的所有影像
- SPSS installation and activation tutorial (including network disk link)
猜你喜欢

Google Earth Engine(GEE)——基于 MCD64A1 的 GlobFire 日常火灾数据集

攻防世界 MISC 进阶 glance-50

sobel过滤器

Challenges faced by virtual human industry
Redis sentinel simply looks at the trade-offs between distributed high availability and consistency

Unity-VScode-Emmylua配置报错解决

Concurrent network modular reading notes transfer

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

Concurrent optimization summary

攻防世界 MISC 高手进阶区 001 normal_png
随机推荐
PostgreSQLSQL高级技巧透视表
MYSQL架构——逻辑架构
攻防世界 MISC 进阶区 Ditf
业务太忙,真的是没时间搞自动化理由吗?
Unity-VScode-Emmylua配置报错解决
Alibaba launched a new brand "Lingyang" and is committed to becoming a "digital leader"
短视频系统源码,点击屏幕空白处键盘不自动收起
Practice and principle of PostgreSQL join
特征缩放 标准化 归一化
Mongodb aggregation operation summary
Why is Dameng data called the "first share" of domestic databases?
How to manage 15million employees easily?
[acwing] solution of the 58th weekly match
Google Earth Engine(GEE)——基于 MCD64A1 的 GlobFire 日常火灾数据集
阿里推出新品牌“瓴羊”,致力成为“数字化领头羊”
Interview essential leetcode linked list algorithm question summary, whole process dry goods!
Postgresqlql advanced skills pivot table
繁华落尽、物是人非:个人站长该何去何从
测试必会:BUG的分类及推进解决
攻防世界 misc 进阶区 2017_Dating_in_Singapore