使用greasemonkey加载和解析远程URL [英] Load and parse remote url with greasemonkey
问题描述
如何编写Greasemonkey脚本,该脚本将通过URL列表(在同一个域中)并在生成的DOM上启用XPath查询?
How can I write a Greasemonkey script that will go through a list of URLs (on the same domain) and enable an XPath query to be performed on the resulting DOM?
谢谢
推荐答案
使用 GM_xmlhttpRequest 和用于HTML解析的createContextualFragment。有关使用createContextualFragment的示例,请参阅 Greasemonkey的最佳插件 。要解析有效的XML,您只需使用 DOMParser.parseFromString 即可。
Use GM_xmlhttpRequest for the request, and createContextualFragment for HTML parsing. See Best Addons for Greasemonkey for an example using createContextualFragment. For parsing of valid XML you can just use DOMParser.parseFromString.
编辑:这是一个非常简单但完整的例子,展示了一切如何融合在一起:
Here's a very simple but complete example to show how everything fits together:
// ==UserScript==
// @name Parse HTML demo
// @namespace
// @include *
// ==/UserScript==
GM_xmlhttpRequest({
method: 'GET',
url: 'http://www.google.com',
onload: function(resp){
var range = document.createRange();
range.setStartAfter(document.body);
var xhr_frag = range.createContextualFragment(resp.responseText);
var xhr_doc = document.implementation.createDocument(null, 'html', null);
xhr_doc.adoptNode(xhr_frag);
xhr_doc.documentElement.appendChild(xhr_frag);
var node = xhr_doc.evaluate("//span//b[@class='gb1']", xhr_doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
GM_log("node.localName: " + node.localName);
GM_log("node.textContent: " + node.textContent);
}
});
这篇关于使用greasemonkey加载和解析远程URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!