Javascript,ajax加载外部页面,重定向断开链接

时间:2011-09-28 18:29:37

标签: javascript ajax

我正在构建一个Chrome扩展程序,可以加载您在搜索结果中单击的链接的实际预览。我分析了出现的链接,并添加了一个处理所有相对URL的<base> url元素。

但是,当我对页面html执行ajax请求,但该页面最终重定向时,我的<base>元素不正确,因为它没有考虑发生的重定向。

要重新迭代,用户点击搜索结果,我会向该网址发送ajax GET请求以接收网页html。我分析了单击的链接,并在插入页面html时添加了适当的<base>元素。 (除了搜索结果的iframe之外,DOM中没有任何其他内容,因此<base>元素不会改变任何其他内容。)

对于没有重定向的任何情况,<base>元素始终是正确的并且效果很好。

当我在Google上搜索“ty”时,www.ty.com会重定向到world.ty.com。如何检测来自world.ty.com的响应?我的<base>元素以www.ty.com

结尾

<小时/> 我正在寻找附加一个检测到404的window.onerror事件,不知怎的,我不知道,纠正了<base>元素。

1 个答案:

答案 0 :(得分:0)

您无法通过XMLHttpRequest对象检索最终的重定向网址。您可以但是,为此创建一个变通方法(用以下代码替换当前的<base>标记):

<!--BEFORE linking any content (at the beggining of HEAD / document-->
<script>
document.write('<base href="'+location.href.replace(/"/g,"%22")+'" />');
</script>

如果您将脚本嵌入到文档中,请使用CDATA部分,或在脚本标记之前添加\,以防止您的网页错误地解析JavaScript代码。

实施示例:

function handleAjaxResponse(html){
  //Searching for `<head>` or `<html>` to insert your HTNL is not reliable:
  // The web master may practice:
  // .. (without html/head tags)..<body> <input value="<head>" /> ....
  html = "<script>" +
   "document.write('<base href=\"'+location.href.replace(/\"/g,'%22')+'\" />')" +
   "<\/script>" + html; //Notice <\/script> !

  //...output html...
}
相关问题