微信页面关闭时接口提交数据
搜索到很多文章说使用同步请求,但真机测试时发现无论ios或安卓都是失败的,请求并没有发送成功。
推荐使用Navigator.sendBeacon()
真机测试IOS及Android都没问题,双端的微信内置浏览器接口也都提交成功
navigator.sendBeacon(url, formData)
react完整请求示例
useEffect(() => {
if (window.addEventListener) {
window.addEventListener("pagehide", function () {
listener()
})
} else {
window.onbeforeunload = function () {
listener();
}
}
}, [])
const listener = () => {
let putData = {
slide_screen: window.scrollY,
screen_height: window.screen.height,
user_token: getStorageSync('user_token'),
}
const formData = new FormData();
Object.keys(putData).forEach((key) => {
let value = putData[key];
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
formData.append(key, value);
});
const url = 'https://xxx.xxxxx.com/api/xx'
if (navigator.sendBeacon) {
navigator.sendBeacon(url, formData)
} else {
const xhr = new XMLHttpRequest()
xhr.open('POST', url, false)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(formData)
}
removeStorageSync('behaviorId')
};
|