2011-11-29 27 views
0

我使用chrome.tabs.executeScript注入的功能作为内容脚本

在注入programaticaly我可以通过如任一

chrome.tabs.executeScript(null, { code: "alert('hello world');"}); 

chrome.tabs.executeScript(null, { file: example.js}); 

我注射按钮按内容脚本可以传入一个字符串或一个文件来执行。有没有办法注入一个函数。

chrome.tabs.executeScript(null, {code: function1}); 

function function1() { alert("hi");} 

回答

2

我认为你不能注入一个内容脚本在后台页面定义的函数。但是,您可以获取函数源代码并立即调用它。

function hello() { alert("hi"); } 

chrome.tabs.executeScript(null, { code: "(" + hello.toString() + ")()" }); 
+0

完美。谢谢。 – Bnicholas

0

如何将函数定义嵌入代码片段本身?

chrome.tabs.executeScript(null, { 
    code: "function function1() { alert('hi'))}; 
      function1();" 
}); 
+0

这个想法是在后台页面中定义多个函数,并只注入需要的函数。这与注入一个声明所有函数的文件相同。 – Bnicholas