Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 sendBeacon 需要注意的问题 #227

Open
funnycoderstar opened this issue Feb 3, 2023 · 0 comments
Open

使用 sendBeacon 需要注意的问题 #227

funnycoderstar opened this issue Feb 3, 2023 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

funnycoderstar commented Feb 3, 2023

fetch和sendBeacon最大的区别

  • fetch:页面销毁时的监控埋点大概率上报失败,优先级为 High
  • sendBeacon:
    • 页面销毁时的监控埋点也发送请求;
    • 在浏览器空闲的时候异步发送数据,不影响页面诸如 JS、CSS Animation 等执行,优先级为 Lowest

需要注意的问题

一、跨域请求

使用 sendBeacon 发跨域请求时,需要注意以下两点

  1. 不能设置 Access-Control-Allow-Origin 为 "*"
  2. 需要设置 Access-Control-Allow-Credentials: true
import cors from "@koa/cors"
app.use(cors({Credentials: true}))

二、接口参数为 json类型时

sendBeacon Data 支持的参数类型如图

image

Fetch post 请求,需要传 http header:

headers: {'Content-Type': 'application/json',}

sendBeacon:使用Blob类型来实现。把Blob内容的格式类型设置为json格式

var data = { ajax_data: 22 };
var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});

// Content-Type of the Beacon HTTP request will be application/json in this case
navigator.sendBeacon('ajax.php', blob);

在 iOS 13 的手机上 发现在端内打开 webview 发生了崩溃,报错信息: iOS 13 不支持 POST body 里面包含 Blob 或者 File 类型的数据。改成使用 fetch 请求后,上述问题不再复现。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant