Skip to content

Instantly share code, notes, and snippets.

@satyr
Forked from cers/gist:102849
Created April 28, 2009 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satyr/102932 to your computer and use it in GitHub Desktop.
Save satyr/102932 to your computer and use it in GitHub Desktop.
// 1. Should also work for <img>, <form>, <link>, etc.
// 2. Should also work for html string, DOM, and XML.
// 3. Should return the same (type of) object it received.
function absolutifyUrls(data, baseUrl) {
switch(typeof data){
case "string":
return data.replace(
/\b(href|src|action)=([\"\']?)(?!https?:\/\/)(\S+)\2/ig,
function au_repl(_, a, q, path)(
a + "=" + q + Utils.url({uri: path, base: baseUrl}).spec + q));
case "object":
jQuery(data).find("a, img, form, link").andSelf().each(function au_each(){
var attr, path = (this.getAttribute(attr = 'href') ||
this.getAttribute(attr = 'src' ) ||
this.getAttribute(attr = 'action'));
if(path !== null && /^(?!https?:\/\/)/.test(path))
this.setAttribute(attr, Utils.url({uri: path, base: baseUrl}).spec);
});
return data;
case "xml":
return XML(arguments.callee(data.toXMLString(), baseUrl));
}
return null;
};
CmdUtils.CreateCommand({
name: "example",
preview: function(pblock) {
pblock.innerHTML = (
"<h3>Tests</h3><br>"
+
absolutifyUrls("<a href='/search?q=ubiquity'>ubiquity</a><br>",
"http://google.com/")
+
absolutifyUrls("<a href='../search?q=ubiquity'>ubiquity</a><br>",
"http://google.com/")
+
absolutifyUrls("<a href='../search?q=ubiquity'>ubiquity</a><br>",
"http://google.com/help")
+
absolutifyUrls("<a href='search?q=ubiquity'>ubiquity</a><br>",
"http://google.com/help")
+
absolutifyUrls("<a href='search?q=ubiquity'>ubiquity</a><br>",
"http://google.com")
+
absolutifyUrls("<a href='search?q=ubiquity'>ubiquity</a><br>",
"http://google.com/")
+
absolutifyUrls("<img src='images/logo.gif'/>",
"http://google.com/intl/en_ALL/")
+
absolutifyUrls(<img src='images/logo.gif'/>,
"http://google.com/intl/en_ALL/").toXMLString()
+
absolutifyUrls(<img src='images/logo.gif'/>,
"http://google.com/intl/en_ALL/").toXMLString()
);
var img = new context.focusedWindow.Image;
img.src = "images/images_hp.gif";
(absolutifyUrls(jQuery("<form target='_blank' action='search'>"+
"<input name='q' value='ubiquity'/>"+
"<input type='submit'/></form>") ,
"http://google.com")
.append(absolutifyUrls(img, "http://google.com/intl/en_ALL/"))
.appendTo(pblock));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment