我相信有些人可能会告诉我,仅仅使用Stylebot来改变页面的CSS,而不是自己的扩展,但是Stylebot太过分了,因此对于我想做的事情来说太笨重了。我只想在每次点击Ctrl+M时扩大左边距100 to。
我想我有两个关键问题:
tab,就像在chrome.browserAction.onClicked.addListener(function(tab)中一样,但无法从文档中确切地知道如何使用。下面是我尝试过的许多内容的一个版本(在background.js中),使用上面链接的SO答案中的代码:
chrome.commands.onCommand.addListener(function(command) {
if (command == "Ctrl+M") {
chrome.tabs.executeScript({code: "$('body').css('margin-left', function(index, curValue) {return parseInt(curValue, 10) + 100 + 'px'}"
});
}
}); 如果这就是问题所在,这就是清单:
{
"name": "MarginAdjust",
"description": "Widen margins of websites with Ctrl+M, narrow them with Ctrl+B.",
"version": "0.1",
"manifest_version": 2,
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"commands": {
"widen_margin": {
"suggested_key": {
"default": "Ctrl+M",
"mac": "Command+M"
},
"description": "Widens margin."
}
}
}谢谢你的指导。我甚至看过Stylebot源代码,试图看看他们是如何做到的,但却无法理解。
编辑:可能是因为我需要一个content_script来修改页面,但显然是scripts
发布于 2014-06-17 09:13:49
内容脚本将在一个特殊的孤立世界中执行。它可以访问注入网页中的DOM节点,并将页面上的JavaScript与扩展中的javascript完全分开。因此,如果您想要插入一段代码,通过使用jQuery库来操作DOM元素,那么首先需要将jQuery库注入到web页面。
chrome.tabs.executeScript(null, {file: "jquery.min.js"});
chrome.tabs.executeScript({code: "$('body').css('margin-left', function(index, curValue) {return parseInt(curValue, 10) + 100 + 'px'});"});内容脚本注入可以通过chrome.command回调触发。onCommand回调的第一个参数的值将是您在manifest.json中声明的命令名。您在"suggested_key“中定义的键组合只有在键尚未分配给其他命令时才会生效。"Ctrl + M“似乎不管用,"Ctrl+Shift+K”也适用于我。
"commands": {
"widen_margin": {
"suggested_key": {
"default": "Ctrl+Shift+K"
},
"description": "Widens margin."
}
}在开发/测试与热键相关的扩展时,还要记住的另一件事是,您需要重新安装扩展,以便检查更新的命令设置。第一次安装时,将采用扩展的命令设置。
我写了一个简单的例子,你可以参考它
manifest.json
{
"name":"MarginAdjust",
"description": "Widen margins of websites with Ctrl+M, narrow them with Ctrl+B.",
"version": "1",
"manifest_version":2,
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"commands": {
"widen_margin": {
"suggested_key": {
"default": "Ctrl+Shift+K"
},
"description": "Widens margin."
}
}
}background.js
chrome.commands.onCommand.addListener(function(command) {
alert(command);
if (command == "widen_margin") {
chrome.tabs.executeScript(null, {file: "jquery.min.js"});
chrome.tabs.executeScript({code: "$('body').css('margin-left', function(index, curValue) {return parseInt(curValue, 10) + 100 + 'px'});"});
}
});https://stackoverflow.com/questions/24254390
复制相似问题