Chrome扩展仅修改popup.html背景色,如何实现修改网页背景色?
Chrome扩展修改网页背景色问题修复
你的问题核心是按钮点击事件调用了错误的函数:你在点击事件里直接调用changeBackgroundColor(color),这个函数运行在popup的上下文里,自然只能修改popup的body背景,根本没触发向目标网页注入脚本的逻辑。
修正步骤
只需要修改popup.js里的按钮点击事件回调,把调用的函数从changeBackgroundColor改成changeBackground:
修正后的popup.js代码:
//popup.js const color = "#ff8346"; //red document.getElementById("colorBtn").addEventListener("click", function(){ // 这里改成调用changeBackground,而非直接操作popup DOM的changeBackgroundColor changeBackground(color); }); function changeBackground(color) { chrome.tabs.query({ active: true, currentWindow: true }, tabs => { chrome.scripting.executeScript({ target: {tabId: tabs[0].id}, function: changeBackgroundColor, args: [color] }); }); } function changeBackgroundColor(color) { document.body.style.backgroundColor = color; }
其他验证说明
- manifest.json里的
scripting和activeTab权限配置正确,无需修改 - popup.html的按钮ID与JS选择器匹配,无问题
修正后重新加载Chrome扩展,打开任意网页点击按钮,就能看到目标网页的body背景色变为设定的#ff8346了。
内容的提问来源于stack exchange,提问作者Robert Gomm
相关产品推荐
相关产品推荐

