在同一来源上发出 XMLHttpRequest 时,有没有办法不发送 cookie?
我正在开发一个为用户解析 gmail rss 提要的扩展程序.如果他们不想保持登录状态,我允许用户指定用户名/密码.但是,如果用户已登录并且提供的用户名/密码用于不同的帐户,则这会中断多次登录.所以我想避免发送任何 cookie,但仍然能够在 send() 调用中发送用户名/密码.
I'm working on an extension that parses the gmail rss feed for users. I allow the users to specify username/passwords if they don't want to stay signed-in. But this breaks for multiple sign-in if the user is signed-in and the username/password provided is for a different account. So I want to avoid sending any cookies but still be able to send the username/password in the send() call.
推荐答案
从 Chrome 42 开始,fetch
API 允许 Chrome 扩展(以及Web 应用程序)来执行无 cookie 请求.HTML5 Rocks 提供了有关使用 fetch API 的介绍性教程.
As of Chrome 42, the fetch
API allows Chrome extensions (and web applications in general) to perform cookie-less requests. HTML5 Rocks offers an introductory tutorial on using the fetch API.
fetch
的高级文档目前非常稀少,但 规范中的 API 接口 是一个很好的起点.接口下面描述的 fetch 算法显示 fetch
生成的请求默认是没有凭据的!
Advanced documentation on fetch
is quite sparse at the moment, but the API interface from the specification is a great starting point. The fetch algorithm described below the interface shows that requests generated by fetch
have no credentials by default!
fetch('http://example.com/').then(function(response) {
return response.text(); // <-- Promise<String>
}).then(function(responseText) {
alert('Response body without cookies:
' + responseText);
}).catch(function(error) {
alert('Unexpected error: ' + error);
});
如果你想要真正的匿名请求,你也可以禁用缓存:
If you want truly anonymous requests, you could also disable the cache:
fetch('http://example.com/', {
// credentials: 'omit', // this is the default value
cache: 'no-store',
}).then(function(response) {
// TODO: Handle the response.
// https://fetch.spec.whatwg.org/#response-class
// https://fetch.spec.whatwg.org/#body
});
相关文章