Today I needed a javascript url resolver to get absolute urls for urls mentioned in css files - resolved against the url of the stylesheet, not the current page. Fortunately, your browser already implements this natively, it's just not exposed in DOM APIs, so it needs a little DOM cleverness to coax out the functionality:
function resolveURL(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; | |
} |
You can play around with it a little here, to see that your browser supports it, too. You should even be able to use a relative URL as the base_url
parameter, which should get resolved against the page url -- which here is the jsfiddle url shown, as that demo is running in an embedded iframe, rather than on this blog itself:
It of course won't work in node.js, but hopefully it'll be useful to something you or others are doing, too. Use as you like; it's all public domain / MIT licensed goodness, whichever you fancy.