A userscript library for easily handling Parsoid DOM trees.
npm install @chlodalejandro/parsoidnotification and Title modules, although they are helpful in ensuring data stability.
js
// The "await" is optional, but ensures that the script has loaded and run before proceeding.
// On the English Wikipedia
await mw.loader.getScript("https://en.wikipedia.org/wiki/User:Chlod/Scripts/ParsoidDocument.js?action=raw&ctype=text/javascript");
// On other wikis, you must upload ParsoidDocument.js from the English Wikipedia or this repository
// first, and then change the URL to lead to the correct page. Make sure to keep the
// ?action=raw&ctype=text/javascript at the end of the URL!
`
If it is available as a gadget, you can instead use the following.
`js
mw.loader.load("ext.gadget.ParsoidDocument"); // where ParsoidDocument is the ID of the gadget.
`
If your userscript is bundled with Webpack, you can also install the @chlodalejandro/parsoid package. This package also adds typings for ParsoidDocument, in case you're developing with TypeScript or a decent IDE with a type checker.
`shell
npm install @chlodalejandro/parsoid
`
Usage
You can then access ParsoidDocument using the ParsoidDocument window global.
`js
const parsoid = new ParsoidDocument();
parsoid.loadPage("User:Chlod/Scripts/ParsoidDocument");
parsoid.document.body.classList.contains("parsoid-body"); // true
// Prints the "data-mw" attribute of all transclusions.
parsoid.document.querySelectorAll("[typeof=\"mw:Transclusion\"]").forEach(v => {
console.log(v.getAttribute("data-mw"));
});
// Convert the document, including any modification, to wikitext.
parsoid.toWikitext();
`
You can also extend the ParsoidDocument class as any other class.
`js
class MyParsoidHandler extends ParsoidDocument {
findAllTransclusions() {
return this.document.querySelectorAll("[typeof=\"mw:Transclusion\"]");
}
}
const parsoid = new MyParsoidHandler();
// ...
parsoid.findAllTransclusions();
`
See also
* types-mediawiki – provides types for the MediaWiki global (mw`).