Response.redirected

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

Response 接口中只读的 redirected 属性表明该响应是否为一个重定向的请求的结果。

备注: 依赖 redirected 过滤重定向很容易导致虚假的重定向阻止你的内容像预期一样生效。因此,当调用 fetch() 时你应该进行过滤操作。详见下面 禁用重定向 的例子。

一个布尔值 (Boolean), 如果响应来自重定向的请求,那么将返回 true.

示例

检测重定向

检测某个响应是否来自一个重定向的请求就如同检测 Response 对象中这个标识一样容易。在下面的代码中,当 fetch 操作引起了重定向,一段文本信息会被插入到元素中。但需要注意的是,这不像下面 禁用重定向 所描述的当重定向不合法时全部阻止的行为一样安全。

js
fetch("awesome-picture.jpg")
  .then(function (response) {
    let elem = document.getElementById("warning-message-box");
    if (response.redirected) {
      elem.innerHTML = "Unexpected redirect";
    } else {
      elem.innerHTML = "";
    }
    return response.blob();
  })
  .then(function (imageBlob) {
    let imgObjectURL = URL.createObjectURL(imageBlob);
    document.getElementById("img-element-id").src = imgObjectURL;
  });

禁用重定向

由于使用 redirected 过滤重定向会允许虚假的重定向,你应该像下面的例子这样,当调用 fetch() 时在 init 参数中设置重定向模式为 "error" :

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

规范

Specification
Fetch
# ref-for-dom-response-redirected①

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
redirected

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见