谷歌瀏覽器插件MV3報錯"Uncaught ReferenceError: window is not defined"
出錯
配置mv3后,在后臺代碼background.js使用DOMPurify發現無法訪問window,會一直報錯
Uncaught ReferenceError: window is not defined
查看后臺,globalThis變成了一個叫ServiceWorkerGlobalScope的玩意
創新互聯長期為近1000家客戶提供的網站建設服務,團隊從業經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態環境。為云夢企業提供專業的成都網站制作、網站設計、外貿網站建設,云夢網站改版等技術服務。擁有10余年豐富建站經驗和眾多成功案例,為您定制開發。
原因
mv3使用了一個叫Service workers的東西替代原來的background頁面,不提供dom API,所以不管是window還是document、HTMLElement……都會xx is not defined
。
chrome官方介紹:
Manifest V3 replaces background pages with service workers.
Like their web page counterparts, extension service workers listen for and respond to events in order to enhance the end user's experience. For web service workers this typically means managing cache, preloading resources, and enabling offline web pages. While extension service workers can still do all of this, the extension package already contains a bundle of resources that can be accessed offline. As such, extension service workers tend to focus on reacting to relevant browser events exposed by Chrome's extensions APIs.
另附mv2和mv3后臺頁區別對比表:
MV2 - Background page MV3 - Service worker Can use a persistent page. Terminates when not in use. Has access to the DOM. Doesn't have access to the DOM. Can use XMLHttpRequest(). Must use fetch() to make requests.
解決
1. 放棄在后臺頁直接調用dom API
chrome官方態度還是比較明確的,所以最好不要花太大力氣去搞。能用chrome API的全都用chrome API實現,特別是標簽和窗口的操作。另外chrome也提供了一些mv2到mv3遷移的建議migrating_to_service_workers
2. 使用undom模擬
undom是比jsdom輕量的Document接口實現,基本滿足dom操作的需求,簡單易用。
安裝
pnpm install --save undom
使用
import undom from 'undom';
let document = undom();
// 簡單操作dom
let foo = document.createElement('foo');
foo.appendChild(document.createTextNode('Hello, World!'));
document.body.appendChild(foo);
// 驅動第三方庫DOMPurify
const purify = DOMPurify(document);
purify.sanitize(html..)
另外undom本身不支持直接輸出HTML,因為它只實現了Document的骨架,不能直接用innerHTML、querySelector等,提供了手動解析的方法
function serialize(el) {
if (el.nodeType===3) return el.textContent;
var name = String(el.nodeName).toLowerCase(),
str = '<'+name,
c, i;
for (i=0; i';
}
function enc(s) {
return s.replace(/[&'"<>]/g, function(a){ return `&#${a};` });
}
// 輸出完整html
console.log(serialize(document.childNodes[0]));
// 轉義html
console.log(enc(serialize(document.childNodes[0])));
文章名稱:谷歌瀏覽器插件MV3報錯"Uncaught ReferenceError: window is not defined"
網頁鏈接:http://www.xueling.net.cn/article/dsojicd.html