最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

detecting a redirect with javascript - how? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Mar 9, 2012 at 17:50 Josh Leitzel 15.2k13 gold badges60 silver badges77 bronze badges asked Mar 9, 2012 at 17:43 burtekburtek 2,6858 gold badges31 silver badges37 bronze badges 4
  • There is an event onbeforeunload, is that what you want? – fardjad Commented Mar 9, 2012 at 17:45
  • @fardjad Maybe I didn't explain it correctly. I need something like this, but with javascript, not php – burtek Commented Mar 9, 2012 at 17:56
  • If it meets the same origin policy you should probably be able to get the 302 header via the XHR object. – zzzzBov Commented Mar 9, 2012 at 18:04
  • Maybe you could use a iframe... Load that url in a iframe and compare its location. Although you might need to work around the cross-domain issue. – MorrisLiang Commented Mar 9, 2012 at 18:05
Add a comment  | 

2 Answers 2

Reset to default 10

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.

Here is simple solution for your question.

x.addEventListener('readystatechange',function(){

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

});
发布评论

评论列表(0)

  1. 暂无评论