Skip to content

Using Google XPath implementation with jsdom

vsemozhetbyt edited this page May 10, 2016 · 3 revisions

As of May 2016, jsdom XPath implementation is a subject to rewrite. If need be, users can use Google XPath implementation with jsdom in several ways.

  1. By injecting the browser version of wgxpath (wgxpath.install.js):
require('jsdom').env({
  url: 'https://www.w3.org/TR/xpath/',
  scripts: [require('path').join(__dirname, 'wgxpath.install.js')],
  // or from Net: [`https://github.com/google/wicked-good-xpath/releases/download/1.3.0/wgxpath.install.js`],
  done: (err, window) => {
    window.wgxpath.install(window, true);
    console.log(window.document.evaluate('.//title', window.document.documentElement,
            null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent);
  }
});
  1. By using Node.js version of wgxpath (wgxpath.install-node.js) as a module:
const wgxpath = require('./wgxpath.install-node.js');

require('jsdom').env({
  url: 'https://www.w3.org/TR/xpath/',
  done: (err, window) => {
    wgxpath.install(window, true);
    console.log(window.document.evaluate('.//title', window.document.documentElement,
            null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent);
  }
});

You can also install the NPM version.

In both cases we use undocumented second argument of wgxpath.install() (see comments here) to redefine XPath methods and properties forcibly.

As for now, Google XPath is faster than jsdom XPath and implements more features (e.g. namespaces).