Chrome扩展:在内容脚本内附加DIV到BODY元素不工作

Chrome extension: appending DIV to BODY element within content script not working

本文关键字:BODY DIV 元素 工作 扩展 脚本 Chrome      更新时间:2023-09-26

在我的谷歌Chrome扩展我想注入一些HTML代码通过附加一个div到BODY元素的网站。我当前的测试内容脚本如下所示:

window.onload = function() {
  $('body').css('background-color', 'blue'); // just for testing
  $('body').append("<div>hello world</div>");
};

背景色变为蓝色。然而,追加DIV似乎不是。至少我在页面或页面源代码中找不到任何东西。我遗漏了什么?

您不需要添加窗口。onload因为内容脚本在页面已经加载时才加载,参见此页。记得在manifest中正确添加权限:

"permissions": [
   "activeTab",
   "tabs",
   "http://*/*", "https://*/*"
],
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["js/contentscript.js"]
  }
]

我假设你的内容脚本将加载所有选项卡,它从js文件夹加载内容脚本。