detecting a redirect with javascript - how?

我是研究僧i 提交于 2019-11-30 02:33:51

问题


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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/9638591/detecting-a-redirect-with-javascript-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!