0

他是我的manifest.json的Chrome扩展 - > ExecuteScript:函数调用没有按”工作

{ 
    "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(); 
    }); 

}); 

铬打造:38.0.2125.111

问题:我究竟做错了什么?为什么在executeScript中调用函数不起作用?

感谢, 浣熊

回答

1

您还没有executeScript调用一个函数

您正在其回调函数中调用该函数,该函数在原始(背景)页面中运行。这是一个函数,描述“executeScript完成时该怎么做”,而不是要运行的代码。

实际运行在您注入代码的页面中的代码是“;” (这显然没有什么)。

可以run a function defined in your codeexecuteScript通过正确地将其转换为字符串。但请注意,它不会访问在函数外部定义的变量。


我认为你是什么试图做的是使代码接受一个参数(颜色)。不要每次都制作自定义代码,您应该考虑使用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" }); 
} 
+0

克桑,谢谢!不,我不试图接受一个参数。这是使用我可以imagein函数的最简单的例子。实际上,我想对表单域进行一些操作,但不想将代码呈现为一个字符串。所以我想把代码放在函数中,并从executeScript中运行它。没有消息可能吗?谢谢,浣熊。 – Racoon 2014-10-29 15:06:35

+0

这是可能的,请参阅[链接的问题](https://stackoverflow.com/questions/25631452/possible-to-pass-anonymous-function-or-reference-to-function-to-executescript/25631544#25631544)。但这不是一个很好的建筑。 – Xan 2014-10-29 15:08:20

+0

如果你想反复运行一些更长的代码,可以考虑把它放在一个js文件中并执行'{file:“filename.js”}'。 – Xan 2014-10-29 15:10:08