How to replace DOMParser in background.js Service Worker

I’m running Firefox Developer Edition 96.0b9 (64-bit) on macOS Monterey 12.1.

My extension is called Context Search. It’s available on Github here and on AMO here.

I’m in the process of converting my extension from manifest 2.0 to manifest 3.0 and read that service workers don’t have access to DOM, so I’m wondering how I can change the following code to meet this requirement:

async function addNewFavicon(id, domain) {
	const optimalSize = '32x32';
	const tests = [ optimalSize, '[.]png', '[.]ico' ];
	let linksWithIcons = [];
	let parser = new DOMParser();
	let bestIconUrl = null;
	let reqHeader = new Headers();
	reqHeader.append('Content-Type', 'text/html; charset=UTF-8');

	const initObject = {
		method: 'GET',
		headers: reqHeader

	const userRequest = new Request(domain, initObject);

	const response = await fetch(userRequest)
		.then((response) => response.text())
		.then((webPage) => {
			const doc = parser.parseFromString(webPage, 'text/html');
			const links = doc.getElementsByTagName('link');
			if (response.status === 200 && response.readyState === 4) {
				// Store all links with a possible favicon in an array
				for (let link of links) {
					const rel = link.getAttribute('rel');
					if (/icon/.test(rel)) {
						const absUrl = convertUrl2AbsUrl(link.href, domain);

				if (logToConsole) console.log(`Domain: ${domain}`);
				if (logToConsole) console.log(`Links with favicons: ${linksWithIcons}`);

				// Check if the links containing icons contain 32x32 in their name, then
				// check if they are of type png. Finally, check if they are of type ico.
				for (let test of tests) {
					if (logToConsole) console.log(`Checking if url contains: ${test}`);
					bestIconUrl = getBestIconUrl(linksWithIcons, test);
					// If an icon is found convert it to a base64 image
					if (bestIconUrl !== null) {
						if (logToConsole) console.log(`Best icon url: ${bestIconUrl}`);
						const base64str = getBase64Image(bestIconUrl);
						return { id: id, base64: base64str };

				// Failed to retrieve a favicon, proceeding with default CS icon
				return { id: id, base64: base64ContextSearchIcon };
		.catch((err) => {
			if (logToConsole) console.log('Something went wrong!', err);
			return({ id: id, base64: base64ContextSearchIcon });
	return response;