常见问题
你好!我正在深入研究Chrome扩展程序的世界,并且在掌握整个工作流程时遇到了一些问题。似乎Google最近转向强烈倡导事件页(Event Pages),而不是将所有内容都放在background.js和background.html中。我认为其中的一部分意思是我们应该将大部分扩展逻辑传递给内容脚本。
在Google的事件页入门指南中,他们在manifest.json文件中列出了内容脚本。但在他们的事件页示例扩展中,它是通过以下代码块在background.js中引入的:chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() { });
使用两种方法各有什么优势呢?
我的代码
我将采用编程方式注入内容脚本,就像Google的示例一样。
manifest.json
{
"manifest_version": 2,
"name": "Test",
"description": "Let's get this sucker working",
"version": "0.0.0.1",
"permissions": [
"tabs",
"*://*/*"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png"
}
}
背景脚本.js
chrome.browserAction.onClicked.addListener(function() {
console.log("alert from background.js");
chrome.tabs.executeScript({file: "jquery-2.0.2.min.js"}, function() {
console.log("jquery Loaded");
});
chrome.tabs.executeScript({file: "content.js"}, function() {
console.log("content loaded");
});
});
content.js
console.log('you\'r in the world of content.js');
var ans = {};
ans.createSidebar = function() {
return {
init: function(){
alert("why hello there");
}
}
}();
ans.createSidebar.init();
我能在后台页面的调试器中看到前三个console.log
语句。我也可以在任何网站中看到来自content.js的提示框。但我无法看到来自content.js的console.log
,也无法查看content.js中的任何JS代码。我尝试查找后台页面调试器的Sources标签下的"content scripts"部分。一些其他帖子中建议添加debugger;
语句以使其显示,但我没有任何好运。我看到的最接近的解决方案是这篇文章,但需要将内容脚本列在清单中。
希望得到任何帮助。谢谢!