使用JavaScript检测重定向-怎么做? [英] detecting a redirect with javascript - how?

查看:77
本文介绍了使用JavaScript检测重定向-怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以知道某个网页是否知道网址,从而将其重定向到另一个网页吗?我的意思是,当您在文本字段中键入URL时,脚本会检查它的3xx重定向。

Is there any way to detect whether a webpage is going to redirect me to another, knowing its URL? I mean the situation when you type URL in a text field and the script examines it for 3xx redirections.

推荐答案

是的,您可以用Javascript很容易做到这一点。看起来像这样:

Yes, you can do this quite easily in Javascript. It'd look something like:

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 设置。如果您想跨任何域统一工作,则必须在服务器端进行。

Unfortunately, this only works on your own server, unless you hit a server with CORS set up. If you wanted to work uniformly across any domain, you're going to have to do it server-side.

这篇关于使用JavaScript检测重定向-怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆