如何检测重定向

detecting a redirect with how?

本文关键字:重定向 检测 何检测      更新时间:2023-09-26

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

是的,在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();

不幸的是,这只适用于您自己的服务器,除非您使用设置了CORS的服务器。如果你想在任何域上统一工作,你就必须在服务器端完成。

以下是您的问题的简单解决方案。

x.addEventListener('readystatechange',function(){
    const url = 'https://your/request/url';
    if(this.responseURL != url){
        alert('redirected');
    }
});