80

我目前正在使用以下函数将相对 URL“转换”为绝对 URL:

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

这在大多数浏览器中运行良好,但 IE6 仍然坚持返回相对 URL!如果我使用 getAttribute('href'),它会做同样的事情。

我能够从 IE6 中获取合格 URL 的唯一方法是创建一个 img 元素并查询它的 'src' 属性 - 问题在于它会生成服务器请求;我想避免的事情。

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


在你推荐一个快速的正则表达式/字符串修复之前,我向你保证它不是那么简单。基本元素 + 双周期相对 url + 大量其他潜在变量真的很糟糕!

必须有一种方法可以做到这一点,而不必创建一个庞大的正则表达式解决方案?

4

11 回答 11

46

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

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

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

于 2009-01-23T12:37:39.010 回答
26

只要浏览器正确实现 <base> 标签,哪些浏览器倾向于:

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;
}

这是一个 jsfiddle,您可以在其中进行试验:http: //jsfiddle.net/ecmanaut/RHdnZ/

于 2012-10-18T23:13:17.283 回答
16

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

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

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

于 2014-06-26T18:31:23.620 回答
10

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

function canonicalize(url) {
    var div = document.createElement('div');
    div.innerHTML = "<a></a>";
    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;
}

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

于 2014-04-07T16:45:39.630 回答
7

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

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

另请参阅http://medialize.github.io/URI.js/docs.html#absoluteto

未使用 IE6 进行测试,但可能对其他搜索一般问题的人有所帮助。

于 2014-01-30T13:31:24.073 回答
7

我实际上想要一种不需要修改原始文档(甚至暂时不需要)但仍然使用浏览器的内置 url 解析等的方法。此外,我希望能够提供自己的基础(如 ecmanaught 的回答)。它相当简单,但使用 createHTMLDocument (可以替换为 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/

于 2015-01-28T01:29:46.093 回答
5

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

/**
 * 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

但是,它不支持其中包含“..”的相对 URL,例如“../file.png”。

于 2013-05-03T20:45:56.457 回答
3

这是我用来解析基本相对 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(/^\.\//, '');
}

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

它既适用于浏览器,也适用于 node.js 或其他环境。

于 2015-01-05T21:36:18.543 回答
2

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

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

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

我将尝试使用 bobince 的解决方案。

于 2011-03-15T22:53:38.773 回答
0

如果url不以'/'开头

取当前页面的 url,去掉最后一个 '/' 之后的所有内容;然后附加相对网址。

否则如果url以'/'开头

获取当前页面的 url 并砍掉单个 '/' 右侧的所有内容;然后附加网址。

否则,如果url以 # 或 ? 开头

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


希望这对你有用

于 2009-01-22T21:37:03.587 回答
-1

如果它在浏览器中运行,这种对我有用..

  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;
  }
于 2012-11-27T10:51:59.727 回答