好。因此,我已经阅读了内容脚本等内容,包括我将在下面添加的其他几篇So文章,但这仍然不起作用!
我的_manifest.json_
:
{
"name": "name",
"version": "1.0",
"description": "desc",
"browser_action": { "default_icon": "icon.png" },
"permissions": [ "tabs", "http://*/*" ],
"background_page": "background.html",
"content_scripts": [ {
"all_frames": true,
"js": [ "content.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
}
我的_background.html_
:
<!doctype html>
<html>
<head>
<title>Background Page</title>
<script src="jquery.min.js"></script>
<script src="content.js"></script>
</head>
<body>
<script>
chrome.browserAction.onClicked.addListener(function(tab)
{
chrome.tabs.executeScript(null, {file:"content.js"});
});
</script>
</body>
</html>
我的_content.js_
:
$('body').prepend('<h1>Testing!</h1>');
$('body').css('background', '#f00 !important');
目前,我只是想修改选项卡主体的背景色。我已经添加了click listener来运行我的background.html文件,但它不起作用。调试时,我在background.html文件中的脚本调用上进行了断点指示,executeScript事件被命中,但我的content.js文件断点没有被命中。我想把content.js文件放在";content_ scripts";在manifest.json文件中就足够了,但如果我删除background.html文件,就不会发生任何事情。
有人能帮我以任何方式修改选项卡的内容吗?!感觉我错过了什么,因为我觉得我比实际情况更难做到。如果有比我想做的更简单的方法,我愿意接受任何建议/最佳实践。
SO研究文章
- 在googlechrome扩展中使用html-dom
- Chrome扩展dom遍历
- 访问dom的Google chrome扩展
- Chrome扩展抓取用于解析的dom内容
后台页面有点像你自己的迷你服务器——它是一个完全独立的页面,与用户访问的页面无关。它用于控制其余的扩展组件,因为它总是在后台运行。
内容脚本是被注入到用户访问的实际页面中的javascript代码,可以访问和修改父页面的DOM。
所以要让你的扩展工作,你需要删除
<script src="jquery.min.js"></script>
<script src="content.js"></script>
从后台页面,并通过manifest:将jquery作为内容脚本注入
"content_scripts": [ {
"all_frames": true,
"js": [ "jquery.min.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ]
或使用chrome.tabs.executeScript
:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file:"jquery.min.js"}, function() {
chrome.tabs.executeScript(null, {file:"content.js"});
});
});
content.js正在尝试使用jQuery,但您还没有将jQuery与内容脚本一起注入到选项卡中。控制台中的错误为"未捕获的ReferenceError:$未定义"。
有两个选项可以用于注入jQuery:
1( 在manifest.json中指定以自动注入jQuery和您的内容脚本:
"js": [ "jquery.min.js", "content.js" ],
或者,
2( 通过background.html注入jQuery:
chrome.tabs.executeScript(null, {file:"jquery.min.js"}, function() {
chrome.tabs.executeScript(null, {file:"content.js"});
});
然后,按下浏览器操作按钮即可工作。