他是我的manifest.json:
{
"name": "Page Redder",
"description": "Make the current page red",
"version": "2.0",
"permissions": [
"activeTab","*://*/*"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon" : "icon.png",
"default_title": "Make this page red"
},
"manifest_version": 2
}
这是可以运行的background.js(页面变成红色):
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {code:'document.body.style.backgroundColor="red";'} );
});
如果我按以下方式更改background.js,它将无法工作:
function changeColor() {
document.body.style.backgroundColor="red";
}
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {code:';'}, function() {
changeColor();
});
});
Chrome 版本:38.0.2125.111
问题:我在这里做错了什么?为什么在executeScript中调用函数不起作用?
谢谢, 浣熊
最佳答案
您没有在 executeScript
中调用函数。
您正在其回调中调用该函数,该函数在原始(后台)页面中运行。它是一个描述“当 executeScript
完成时要做什么”的函数,而不是要运行的代码。
在您注入(inject)代码的页面中实际运行的代码是“;” (这显然什么也没做)。
你可以 run a function defined in your code通过将其正确转换为字符串来使用 executeScript
。但请注意,它无法访问函数外部定义的变量。
我认为您尝试要做的是让代码接受参数(颜色)。您应该考虑使用Messaging,而不是每次都编写自定义代码。传递命令。
示例:添加包含以下内容的文件 content.js
:
// Include guard: only execute once
if (!injected) {
injected = true;
init();
}
function init() {
// Get ready to receive a command
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if(message.action == "colorBackground") {
document.body.style.backgroundColor = message.color;
}
});
}
在您的后台,您可以执行以下操作:
chrome.tabs.executeScript(null, {file: "content.js"}, function() {
// File executed, it's ready for the message
chrome.tabs.sendMessage(null, { action: "backgroundColor", color: "green" });
}
关于javascript - Chrome 扩展 -> 执行脚本 : function call doesn' work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26633457/