Bnicholas
Bnicholas

Reputation: 14121

Inject a function as a content script

I am injecting a content script on button press using chrome.tabs.executeScript

When injecting programaticaly I can pass in as either

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

or

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

I can pass in a string or a file to execute. Is there a way to inject a function.

something like

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

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

Upvotes: 0

Views: 1052

Answers (2)

Mike Fahy
Mike Fahy

Reputation: 5707

How about embedding the function definition within the code snippet itself?

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

Upvotes: 0

check_ca
check_ca

Reputation: 51

I think you can't inject into a content script a function defined in a background page. However, you can get the function source code and make it immediately invoked.

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

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

Upvotes: 2

Related Questions