Skip to content

Instantly share code, notes, and snippets.

@asm256
Last active August 29, 2015 14:04
Show Gist options
  • Save asm256/54a5327db50607678b62 to your computer and use it in GitHub Desktop.
Save asm256/54a5327db50607678b62 to your computer and use it in GitHub Desktop.
portable gm_xpath
//@original https://github.com/scriptish/scriptish/blob/master/extension/modules/api/sandboxScripts.js
// を元にchrome上で動く用に改変
//@howto https://github.com/scriptish/scriptish/wiki/GM_xpath
//require https://gist.github.com/54a5327db50607678b62.txt
//頭に@つけてuser.jsに書くと楽
if(typeof(GM_xpath) != "function"){
function GM_xpath(details) {
var contextNode, contextDocument, paths, resolver, namespace, result,path;
if (typeof(details) == 'string') {
details = { path: details }
}
contextNode = "node" in details ? details.node : document;
if (!contextNode) {
throw new Error("The value specified for node is invalid");
}
if (contextNode.ownerDocument) {
contextDocument = contextNode.ownerDocument;
}
else if (contextNode.evaluate) {
// contextNode is a Document already
contextDocument = contextNode;
}
else {
throw new Error("No owning document for the specified node. Make sure you pass a valid node!");
}
paths = details.paths || details.path;
if (typeof(paths) == "string") {
paths = [paths];
}
if (details.resolver) {
if (typeof(details.resolver) == "string") {
resolver = {lookupNamespaceURI: function(p){return details.resolver;}};
}
else if (typeof(details.resolver) == "function") {
resolver = {lookupNamespaceURI: details.resolver};
}
else if (typeof(resolver.lookupNamespaceURI) == "function") {
resolver = details.resolver;
}
else {
throw new Error("resolver is invalid");
}
}
else if (contextNode.namepaceURI) {
namespace = contextNode.namespaceURI;
resolver = {lookupNamespaceURI: function(p){return namespace;}};
}
if (details.all) {
var rv = [], n;
while (path = paths.shift()) {
result = contextDocument.evaluate(
path,
contextNode,
resolver,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null
);
while (n = result.iterateNext()) {
rv.push(n);
}
}
return rv;
}
while (path = paths.shift()) {
result = contextDocument.evaluate(
path,
contextNode,
resolver,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;
if (result) {
return result;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment