使用greasemonkey加载和解析远程url

Dav*_*ave 1 javascript url greasemonkey

我如何编写一个 Greasemonkey 脚本来遍历 URL 列表(在同一域中)并启用对生成的 DOM 执行 XPath 查询?

谢谢

Mat*_*hen 5

对请求使用GM_xmlhttpRequest,对 HTML 解析使用createContextualFragment。有关使用 createContextualFragment 的示例,请参阅Greasemonkey 的最佳插件。为了解析有效的 XML,您可以只使用DOMParser.parseFromString

编辑:这是一个非常简单但完整的示例,用于展示所有内容如何组合在一起:

// ==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);
    }
});
Run Code Online (Sandbox Code Playgroud)