使用javascript检测重定向 - 如何?

bur*_*tek 13 javascript redirect detection

有没有办法检测网页是否会将我重定向到另一个网页,知道它的URL?我的意思是当您在文本字段中键入URL并且脚本检查它是否为3xx重定向时的情况.

sam*_*aml 5

是的,您可以使用Javascript轻松完成此操作。它看起来像:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
  if (this.status < 400 && this.status >= 300) {
    alert('this redirects to ' + this.getResponseHeader("Location"));
  } else {
    alert('doesn\'t redirect ');
  }
}
xhr.open('HEAD', '/my/location', true);
xhr.send();
Run Code Online (Sandbox Code Playgroud)

不幸的是,除非您在设置了CORS的服务器上运行,否则这仅适用于您自己的服务器。如果您想跨任何域统一工作,则必须在服务器端进行。

  • 我在这里可能是错的,但我认为这可能不起作用,检查您是否被重定向的唯一方法是检查 **responseURL** 属性 https://xhr.spec.whatwg.org/#the-responseurl- attribute 如果不同,则 **open** 方法中使用的 URL 存在重定向 (2认同)