Chrome扩展Content JavaScript无法加载问题求助
问题解决步骤
1. 修正manifest.json结构错误
你的content_scripts配置被错误嵌套在action字段里了,Chrome扩展Manifest V3中,content_scripts是和action同级的顶层字段,并非action的子属性——这直接导致content.js完全没被注入页面,所以开头的console.log也不会输出。同时icons字段原本也嵌套在action内,同样需要移到顶层,否则扩展图标可能无法正常显示。
修正后的manifest.json:
{ "manifest_version": 3, "name": "Ziggify", "description": "Turn images to Zig!", "version": "1.0", "action": { "default_popup": "zig.html", "default_icon": "images/pig_32.png" }, "icons":{ "16":"images/pig_16.png", "32":"images/pig_32.png", "48":"images/pig_48.png", "128":"images/pig_128.png" }, "content_scripts": [{ "all_frames":true, "matches": ["<all_urls>"], "js": ["js/content.js"] }] }
2. 修复JavaScript循环越界问题
你的循环条件i<=img.length会导致最后一次循环访问img[img.length]——这个位置不存在对应元素,会抛出错误中断代码执行,应该改成i < img.length。另外getElementsByTagName永远返回HTMLCollection对象(不会是null),判断长度是否大于0更准确。
修正后的content.js:
console.log("help"); var img = document.getElementsByTagName("img"); if(img.length > 0){ for (let i=0; i < img.length; i++){ img[i].setAttribute("src","https://ziggysaidgrub.github.io/images/piggies.jpg/"); } }
如果想避免实时HTMLCollection的潜在问题(修改DOM时集合会动态变化),可以转成数组后遍历:
console.log("help"); var imgs = Array.from(document.getElementsByTagName("img")); imgs.forEach(img => { img.setAttribute("src","https://ziggysaidgrub.github.io/images/piggies.jpg/"); });
3. 验证扩展生效
修改代码后,在Chrome扩展管理页面点击「重新加载」按钮,刷新目标页面,打开页面控制台(不是扩展后台控制台)就能看到"help"日志,同时图片会被替换。
内容的提问来源于stack exchange,提问作者Grub
相关产品推荐
相关产品推荐

