2

I would like to write a greasemonkey script that given an xpath returns all of the output of that xpath executed on the current page in a .txt file with one result per row.

How do I do this?

EDIT: Its ok if the output is not written to a file. I just want to have it displayed.

1 Answers1

1

Here is an example that appends a list of all href links to the body of the html. You can pretty it up with style, and make it hidden, floating, etc.

// ==UserScript==
// @name           test
// @namespace      johnweldon.com
// @description    test
// @include        *
// ==/UserScript==

(function() { 
    try {
        var xpath = "//a[@href]";                // get all links
        var res = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,  null);
        var str = "<div><ul>";
        for ( var i = 0; i < res.snapshotLength; i++) {
            str = str + "\n<li>" + res.snapshotItem(i);
        }
        str += "</ul></div>";

        var ev = document.createElement("div");  // parent element for our display
        ev.innerHTML = str;                      //quick and dirty
        document.body.appendChild(ev);
    }
    catch (e) {
        alert(e.message);
    }
}())
John Weldon
  • 39,849
  • 11
  • 94
  • 127
  • I suppose there is a missing `+ ""` at the end of the statement in the for loop. – hlovdal Oct 25 '14 at 13:28
  • @hlovdal not really; see this SO discussion about closing `li` tags: http://stackoverflow.com/questions/20550788/does-the-li-tag-in-html-have-an-ending-tag – John Weldon Oct 25 '14 at 15:52