如何使用JavaScript获取URL的重定向目标?

时间:2017-03-08 14:13:31

标签: javascript redirect

the Stack Exchange editor's image uploader doesn't like URL redirects以来,我试图查看是否可以编写可以完成工作的用户脚本。基本上,给定一个URL http://foo.bar,我需要获得最终的重定向位置。

XmlHTTPRequest$.ajax()不实用,因为目标网站可能不允许这样做:

  

XMLHttpRequest无法加载https:// ....   '访问控制允许来源'标题出现在请求的上   资源。起源' http://meta.stackexchange.com'因此不是   允许访问。

1 个答案:

答案 0 :(得分:0)

好吧,因为CORS,你需要某种服务器旁路脚本。在PHP中,它看起来像这样:

$content  = file_get_contents($_POST['url']);
foreach($http_response_header as $header) {
   if (!preg_match('/^Location:(.*)$/i', $header, $location)) {
       $location = false;
   }
}
header('Content-type: application/json');
if ($location) {
    echo '{"hasRedirection": true, "location": "'.$location[1].'"}';
} else {
    echo '{"hasRedirection": false}';
}

让我们将“bypass.php”调用到包含这段代码的文件中。顺便说一下,它是一个未经测试的代码,所以要小心。

现在,您可以使用AJAX调用来确定目标网址是否具有重定向,只需向bypass.php发送一个帖子请求,其中包含保存目标网址的帖子字段url