2

I'm trying to manipulate an HTML string in the background script, that in the chrome extension V3 is using a service worker.

In the migration documentation it is mentions to use jsdom in order to get access to the DOMParser: https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/#documents

The problem is that when I try to add jsdom, I receive the following error: background script error

The manifest the background script is defined as:

"background": {
    "service_worker": "background.js"
},
"manifest_version": 3,
....

The background script contains the following code:

const jsdom = require("jsdom");
const dom = new jsdom.JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log("textContent", dom.window.document.querySelector("p").textContent); // 'Hello world'

My question is: How does one get access to DOMParser in the V3 chrome extension inside the service worker?

bluscience
  • 223
  • 3
  • 7
  • 5
    You need to use browserfy to produce a bundle out of jsdom. Last time I tried it was 5MB minified so I realized that MV3 is still a total joke and I had to find another small regexp-based library to parse html instead, which is of course ridiculous in itself. – wOxxOm Nov 30 '21 at 19:43
  • 1
    5MB that's a lot, but did it worked after you used browserfy? I was thinking of using regex, but it's a very dynamic extension and it won't without DOMParser – bluscience Nov 30 '21 at 20:00
  • If your needs are not too complex, you can get away with scraping using the jQuery library, like this person: https://junchenghan.com/2019/03/28/my-first-chrome-extension/ – thdoan Jan 10 '22 at 20:45
  • 2
    I think that jQuery is using the DOM (document) to manipulate the data and you don't have access to the DOM in a service worker. I manage to get it work with a similar approach to jQuery using cheerio js – bluscience Jan 11 '22 at 08:22

0 Answers0