拡張機能のservice workerでXMLをパースする
Chrome拡張機能のBackground(service worker)でXMLのパースをするのは少々厄介です。本記事ではその問題点と解決方法を解説します。
問題点
通常、XMLを手っ取り早くパースするならDOMParserを使って次のように書きます。
const xmlDataStr = '<root a="nice" ><a>wow</a></root>';const parser = new DOMParser();const xml = parser.parseFromString(xmlDataStr, "text/xml");console.log(xml.querySelector("root"));しかしservice workerではDOMへアクセスできないため、DOMParserは使えません。
service workerで上記を実行するとDOMParserは未定義だと怒られます。
ReferenceError: DOMParser is not defined解決方法
DOMParserを使わずライブラリを使ってしまえば解決できます。
筆者はfast-xml-parserを使いました。
import { XMLParser } from "fast-xml-parser";
const xmlDataStr = '<root a="nice" ><a>wow</a></root>';const parser = new XMLParser({ ignoreAttributes: false });console.log(parser.parse(xmlDataStr));次のテキストがパース結果です。
{ root: { a: 'wow', '@_a': 'nice' } }属性の取得
属性も取得する場合はignoreAttributesをfalseにしておきます。
属性のキーは@_aのように属性名の前にprefixとして@_がつきます。
fast-xml-parserのドキュメントはリポジトリのdocsディレクトリにあります。他のXMLParserのオプションを知りたい場合はその公式ドキュメント2.XMLparseOptions.mdを読みましょう。
以上、service workerでXMLをパースする方法でした。拡張機能のBackgroundを書いていると意外と「〇〇が動かない!そうか、DOM……」となりがちですね。