【发布时间】:2013-06-11 17:54:31
【问题描述】:
一般问题
你好!我正在深入研究 Chrome 扩展程序的世界,并且在降低整个工作流程方面遇到了一些问题。谷歌最近似乎转而大力提倡事件页面,而不是将所有内容都保存在 background.js 和 background.html 中。我部分理解这意味着我们应该将您的大部分扩展逻辑传递给内容脚本。
在Google's Event Page primer 中,它们的内容脚本列在 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"
}
}
background.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();
我能够让前 3 个console.log 语句显示在后台页面的调试器中。我还可以从 content.js 获取警报以显示在任何网站上。但是我无法从 content.js 中看到console.log,也无法从 content.js 中查看任何 JS。我尝试查看后台页面调试器的“源”选项卡的“内容脚本”部分。 SO 上的其他一些帖子建议添加debugger; 语句以使其显示,但我没有任何运气。我见过的最接近的解决方案是this post,但通过在清单中列出内容脚本来完成。
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
你的问题解决了我的问题。通过清单注入内容脚本,我无法真正与网页的 DOM 进行交互。现在,通过 browser_action 加载 contentScript 解决了我的问题。谢谢。赞赏。
标签: debugging google-chrome-extension google-chrome-devtools content-script