Response: redirected 属性

Baseline 已广泛支持

此功能已非常成熟,可在多种设备和浏览器版本上使用。自 2017 年 10 月以来,它已在各大浏览器中可用。

注意:此功能在 Web Workers 中可用。

redirectedResponse 接口的一个只读属性,用于指示响应是否是你发起的请求被重定向后的结果。

注意: 不推荐通过检查 redirected 属性来阻止重定向,因为当响应被接收时,重定向已经发生,并且你可能已经将请求发送到了一个非预期的目的地,甚至可能发送了敏感信息。相反,你应该在调用 fetch() 时进行过滤。请参阅 阻止重定向 示例,其中展示了如何做到这一点。

一个布尔值,如果响应表明你的请求已被重定向,则为 true

示例

检测重定向

要检查响应是否来自被重定向的请求,只需检查 Response 对象上的此标志即可。在下面的代码中,当 fetch 操作期间发生重定向时,会在一个元素中插入文本消息。但请注意,这不像下文 阻止重定向 中描述的那样,可以立即拒绝意外的重定向。

url 属性返回重定向后的最终 URL。

js
fetch("awesome-picture.jpg")
  .then((response) => {
    const elem = document.getElementById("warning-message-box");
    elem.textContent = response.redirected ? "Unexpected redirect" : "";
    // final url obtained after redirects
    console.log(response.url);
    return response.blob();
  })
  .then((imageBlob) => {
    const imgObjectURL = URL.createObjectURL(imageBlob);
    document.getElementById("img-element-id").src = imgObjectURL;
  });

阻止重定向

检查 redirected 是阻止重定向的糟糕方法,因为重定向已经发生。相反,你应该在调用 fetch()options 参数中将重定向模式设置为 "error",如下所示:

js
fetch("awesome-picture.jpg", { redirect: "error" })
  .then((response) => response.blob())
  .then((imageBlob) => {
    const imgObjectURL = URL.createObjectURL(imageBlob);
    document.getElementById("img-element-id").src = imgObjectURL;
  });

规范

规范
Fetch
# ref-for-dom-response-redirected①

浏览器兼容性

另见