开发者

Javascript, ajax loading external page, redirect breaks links

I am building a chrome extension tha开发者_如何学Got loads a real preview of links you click in your search results. I analyze the links that come up, and add a <base> url element that handles all relative urls.

However, when I do an ajax request for a pages html, but that page ultimately redirects, my <base> element is incorrect because it does not take into account the redirect that happened.

To re-iterate, A user clicks a search result, I send an ajax GET request to that url to receive the pages html. I analyze the link that was clicked, and add an appropriate <base> element when I insert the pages html. (There isn't anything else in the DOM other than an iframe of the search results, so the <base> element doesn't alter anything else.)

For any situation that doesn't have a redirect, the <base> element is always correct and works great.

When I search 'ty' on google, www.ty.com redirects to world.ty.com. How can I detect the response came from world.ty.com?  My <base> element ends up with www.ty.com


I am looking at attaching a window.onerror event that detects a 404 and somehow, I have no idea, corrects the <base> element.


You cannot retrieve the final, redirected URL through the XMLHttpRequest object. You can however, create a workaround for this (replace your current <base> tag by the following code):

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

If you embed your script in the document, either use CDATA sections, or add a \ before the script tag, to prevent your page from incorrectly parsing the JavaScript code.

Example of an implementation:

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...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜