一般的问题
你好!我正在深入研究 Chrome 扩展程序的世界,并且在降低整个工作流程方面遇到了一些问题。谷歌最近似乎转而大力提倡事件页面,而不是将所有内容都保存在 background.js 和 background.html 中。我认为这意味着我们应该将您的大部分扩展逻辑传递给内容脚本。
在Google 的 Event Page Primer中,他们在 manifest.json 文件中列出了内容脚本。但是在他们的事件页面示例扩展中,它是通过 background.js 中的这个代码块引入的:chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() { });
一种方式比另一种方式有什么优势?
我的代码
我将继续使用注入内容脚本的编程方式,例如 Google 的示例。
清单.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");
});
});
内容.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();
我能够让前 3 个console.log
语句显示在后台页面的调试器中。我还可以从 content.js 获取警报以显示在任何网站上。但是我无法看到console.log
来自 content.js 的内容,也无法查看来自 content.js 的任何 JS。我尝试查看后台页面调试器的“源”选项卡的“内容脚本”部分。SO上的其他一些帖子建议添加debugger;
语句以使其显示,但我没有任何运气。我见过的最接近的解决方案是这篇文章,但它是通过在清单中列出内容脚本来完成的。
任何帮助,将不胜感激。谢谢!