Response.redirected - Web APIs 编辑

The read-only redirected property of the Response interface indicates whether or not the response is the result of a request you made which was redirected.

Relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected. Instead, you should actually instead do the filtering when you call fetch(). See the example Disallowing redirects, which shows this being done.

Syntax

var isRedirected = Response.redirected;

Value

A Boolean which is true if the response indicates that your request was redirected.

Examples

Detecting redirects

Checking to see if the response comes from a redirected request is as simple as checking this flag on the Response object. In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under Disallowing redirects below.

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;
});

Disallowing redirects

Because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this:

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;
});

Specifications

SpecificationStatusComment
Fetch
The definition of 'redirected' in that specification.
Living StandardInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:133 次

字数:4474

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文