热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从相对URL获取绝对URL。(IE6的问题)-GettinganabsoluteURLfromarelativeone.(IE6issue)

ImcurrentlyusingthefollowingfunctiontoconvertarelativeURLtoanabsoluteone:我现在使用以下函数

I'm currently using the following function to 'convert' a relative URL to an absolute one:

我现在使用以下函数将相对URL“转换”为绝对的URL:

function qualifyURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.href;
}

This works quite well in most browsers but IE6 insists on returning the relative URL still! It does the same if I use getAttribute('href').

这在大多数浏览器中都很好用,但是IE6仍然坚持返回相对URL !如果我使用getAttribute('href'),它也会这样做。

The only way I've been able to get a qualified URL out of IE6 is to create an img element and query it's 'src' attribute - the problem with this is that it generates a server request; something I want to avoid.

我能从IE6获得合格URL的唯一方法是创建一个img元素并查询它的“src”属性——问题是它生成一个服务器请求;这是我要避免的。

So my question is: Is there any way to get a fully qualified URL in IE6 from a relative one (without a server request)?

所以我的问题是:是否有办法从一个相对的IE6中获得一个完全合格的URL(没有服务器请求)?


Before you recommend a quick regex/string fix I assure you it's not that simple. Base elements + double period relative urls + a tonne of other potential variables really make it hell!

在您推荐一个快速的regex/string修复之前,我向您保证它不是那么简单。基础元素+双周期相对url +一吨其他潜在变量真的让它地狱!

There must be a way to do it without having to create a mammoth of a regex'y solution??

一定有一种方法可以做到这一点,而不需要创建一个庞大的regex'y解决方案?

11 个解决方案

#1


46  

How strange! IE does, however, understand it when you use innerHTML instead of DOM methods.

多么奇怪!但是,当您使用innerHTML而不是DOM方法时,IE会理解它。

function escapeHTML(s) {
    return s.split('&').join('&').split('<').join('<').split('"').join('"');
}
function qualifyURL(url) {
    var el= document.createElement('div');
    el.innerHTML= 'x';
    return el.firstChild.href;
}

A bit ugly, but more concise than Doing It Yourself.

有点丑,但比你自己做更简洁。

#2


27  

As long as the browser implements the tag correctly, which browsers tend to:

只要浏览器正确实现了标签,浏览器倾向于:

function resolve(url, base_url) {
  var doc      = document
    , old_base = doc.getElementsByTagName('base')[0]
    , old_href = old_base && old_base.href
    , doc_head = doc.head || doc.getElementsByTagName('head')[0]
    , our_base = old_base || doc_head.appendChild(doc.createElement('base'))
    , resolver = doc.createElement('a')
    , resolved_url
    ;
  our_base.href = base_url || '';
  resolver.href = url;
  resolved_url  = resolver.href; // browser magic at work here

  if (old_base) old_base.href = old_href;
  else doc_head.removeChild(our_base);
  return resolved_url;
}

Here's a jsfiddle where you can experiment with it: http://jsfiddle.net/ecmanaut/RHdnZ/

这里有一个jsfiddle,您可以使用它:http://jsfiddle.net/ecmanaut/RHdnZ/

#3


13  

You can make it work on IE6 just cloning the element:

你可以让它在IE6上工作只是克隆元素:

function qualifyURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.cloneNode(false).href;
}

(Tested using IETester on IE6 and IE5.5 modes)

(使用IE6和IE5.5模式测试)

#4


9  

I found on this blog another method that really looks like @bobince solution.

我在这个博客上发现了另一种方法,看起来真的像@bobince解决方案。

function canonicalize(url) {
    var div = document.createElement('div');
    div.innerHTML = "";
    div.firstChild.href = url; // Ensures that the href is properly escaped
    div.innerHTML = div.innerHTML; // Run the current innerHTML back through the parser
    return div.firstChild.href;
}

I found it a little more elegant, not a big deal.

我觉得它更优雅一点,没什么大不了的。

#5


6  

URI.js seems to solve the issue:

URI。js似乎解决了这个问题:

URI("../foobar.html").absoluteTo("http://example.org/hello/world.html").toString()

See also http://medialize.github.io/URI.js/docs.html#absoluteto

参见http://medialize.github.io/URI.js/docs.html absoluteto

Not testeed with IE6, but maybe helpful for others searching to the general issue.

虽然没有被IE6测试过,但是可能对搜索一般问题的其他人有帮助。

#6


6  

I actually wanted an approach to this that didn't require modifying the original document (not even temporarily) but still used the browser's builtin url parsing and such. Also, I wanted to be able to provide my own base (like ecmanaught's answer). It's rather straightforward, but uses createHTMLDocument (could be replaced with createDocument to be a bit more compatible possibly):

实际上,我希望有一种方法,不需要修改原始文档(甚至是暂时的),但仍然使用浏览器的内置url解析等等。同时,我希望能够提供我自己的基础(如ecmanaught的答案)。它非常简单,但是使用了createHTMLDocument(可以用createDocument替换为createDocument,以便更兼容一些):

function absolutize(base, url) {
    d = document.implementation.createHTMLDocument();
    b = d.createElement('base');
    d.head.appendChild(b);
    a = d.createElement('a');
    d.body.appendChild(a);
    b.href = base;
    a.href = url;
    return a.href;
}

http://jsfiddle.net/5u6j403k/

http://jsfiddle.net/5u6j403k/

#7


5  

This solution works in all browsers.

此解决方案适用于所有浏览器。

/**
 * Given a filename for a static resource, returns the resource's absolute
 * URL. Supports file paths with or without origin/protocol.
 */
function toAbsoluteURL (url) {
  // Handle absolute URLs (with protocol-relative prefix)
  // Example: //domain.com/file.png
  if (url.search(/^\/\//) != -1) {
    return window.location.protocol + url
  }

  // Handle absolute URLs (with explicit origin)
  // Example: http://domain.com/file.png
  if (url.search(/:\/\//) != -1) {
    return url
  }

  // Handle absolute URLs (without explicit origin)
  // Example: /file.png
  if (url.search(/^\//) != -1) {
    return window.location.origin + url
  }

  // Handle relative URLs
  // Example: file.png
  var base = window.location.href.match(/(.*\/)/)[0]
  return base + url

However, it doesn't support relative URLs with ".." in them, like "../file.png".

但是,它不支持带有“.. .”的相对url,比如“../file.png”。

#8


3  

This is the function I use to resolve basic relative URLs:

这是我用来解析基本相对url的函数:

function resolveRelative(path, base) {
    // Absolute URL
    if (path.match(/^[a-z]*:\/\//)) {
      return path;
    }
    // Protocol relative URL
    if (path.indexOf("//") === 0) {
      return base.replace(/\/\/.*/, path)
    }
    // Upper directory
    if (path.indexOf("../") === 0) {
        return resolveRelative(path.slice(3), base.replace(/\/[^\/]*$/, ''));
    }
    // Relative to the root
    if (path.indexOf('/') === 0) {
        var match = base.match(/(\w*:\/\/)?[^\/]*\//) || [base];
        return match[0] + path.slice(1);
    }
    //relative to the current directory
    return base.replace(/\/[^\/]*$/, "") + '/' + path.replace(/^\.\//, '');
}

Test it on jsfiddle: https://jsfiddle.net/n11rg255/

在jsfiddle进行测试:https://jsfiddle.net/n11rg255/

It works both in the browser and in node.js or other environments.

它在浏览器和节点中都可以工作。js或其他环境。

#9


2  

I found this blog post that suggests using an image element instead of an anchor:

我发现这篇博文建议使用图像元素而不是锚点:

http://james.padolsey.com/Javascript/getting-a-fully-qualified-url/

http://james.padolsey.com/Javascript/getting-a-fully-qualified-url/

That works to reliably expand a URL, even in IE6. But the problem is that the browsers that I have tested will immediately download the resource upon setting the image src attribute - even if you set the src to null on the next line.

这可以可靠地扩展URL,即使在IE6中也是如此。但是问题是,我测试过的浏览器会在设置image src属性时立即下载资源——即使您在下一行将src设置为null。

I am going to give bobince's solution a go instead.

我打算尝试一下布宾斯的方法。

#10


0  

If url does not begin with '/'

如果url不以'/'开头

Take the current page's url, chop off everything past the last '/'; then append the relative url.

获取当前页面的url,删除所有超过最后一个'/'的内容;然后追加相关url。

Else if url begins with '/'

否则,如果url以'/'开头

Take the current page's url and chop off everything to the right of the single '/'; then append the url.

获取当前页面的url并将所有内容删除到单个'/'的右边;然后添加url。

Else if url starts with # or ?

如果url以#开头,或者?

Take the current page's url and simply append url

获取当前页面的url并简单地附加url


Hope it works for you

希望它对你有用。

#11


0  

If it runs in the browser, this sort of works for me..

如果它在浏览器中运行,这对我来说是可行的。

  function resolveURL(url, base){
    if(/^https?:/.test(url))return url; // url is absolute
    // let's try a simple hack..
    var basea=document.createElement('a'), urla=document.createElement('a');
    basea.href=base, urla.href=url;
    urla.protocol=basea.protocol;// "inherit" the base's protocol and hostname
    if(!/^\/\//.test(url))urla.hostname=basea.hostname; //..hostname only if url is not protocol-relative  though
    if( /^\//.test(url) )return urla.href; // url starts with /, we're done
    var urlparts=url.split(/\//); // create arrays for the url and base directory paths
    var baseparts=basea.pathname.split(/\//); 
    if( ! /\/$/.test(base) )baseparts.pop(); // if base has a file name after last /, pop it off
    while( urlparts[0]=='..' ){baseparts.pop();urlparts.shift();} // remove .. parts from url and corresponding directory levels from base
    urla.pathname=baseparts.join('/')+'/'+urlparts.join('/');
    return urla.href;
  }

推荐阅读
author-avatar
一达通治蓬_832
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有