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 set contentType #212

Open
funnycoderstar opened this issue Sep 26, 2022 · 0 comments
Open

sendBeacon set contentType #212

funnycoderstar opened this issue Sep 26, 2022 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

funnycoderstar commented Sep 26, 2022

sendBeacon 设置 contentType

如果是 post 请求,需要传 http header:

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

对应的 fetch 请求是可以这样的,但是 sendBeacon 好像不支持这种。

sendBeacon 有下面三种参数传递方式

  1. contentType: application/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);

这种情况下如果是跨域请求可能是报错跨域错误,详情可查看 sendBeacon cors error

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

  1. contentType: multipart/form-data
var fd = new FormData();
fd.append('ajax_data', 22);
navigator.sendBeacon('ajax.php', fd);
  1. contentType: application/x-www-form-urlencoded
var params = new URLSearchParams({ ajax_data: 22 })
navigator.sendBeacon('ajax.php', params);

参考文档

https://requestmetrics.com/building/using-the-beacon-api
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
https://usefulangle.com/post/63/javascript-navigator-sendbeacon-set-form-http-header

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