XMLHttpRequest: withCredentials 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

注意:此功能在 Web Workers 中可用,但 Service Workers 除外。

XMLHttpRequest.withCredentials 属性是一个布尔值,用于指示是否应使用 Cookie、身份验证标头或 TLS 客户端证书等凭据进行跨站 Access-Control 请求。设置 withCredentials 对同源请求没有影响。

此外,此标志还用于指示何时应在响应中忽略 Cookie。默认值为 false。除非在发出请求前将 withCredentials 设置为 true,否则来自不同域的 XMLHttpRequest 响应无法为其自身域设置 Cookie 值。通过将 withCredentials 设置为 true 获取的第三方 Cookie 仍会遵守同源策略,因此请求脚本无法通过 document.cookie 或响应标头访问它们。

注意:这永远不会影响同源请求。

注意: 无论 Access-Control- 标头值如何,来自不同域的 XMLHttpRequest 响应在发出请求前未将 withCredentials 设置为 true 的情况下,*无法* 为其自身域设置 Cookie 值。

布尔值。

示例

js
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/", true);
xhr.withCredentials = true;
xhr.send(null);

规范

规范
XMLHttpRequest
# the-withcredentials-attribute

浏览器兼容性