mcabrams
mcabrams

Reputation: 684

Possible to pass anonymous function or reference to function to executeScript?

Is it possible to pass an anonymous function to the chrome API executeScript call? Currently I have the following code:

chrome.tabs.executeScript(tab.id, {code: "document.body.appendChild(document.createElement('p'));"})

Is there a way to pass the code I want executed as a function reference, rather than a string? I know of the file option, but I'd prefer to just pass a reference to a function already provided in bg.js. I don't like the string because I lose syntax highlighting/formatting in my editor, amongst other reasons.

Upvotes: 4

Views: 495

Answers (1)

Xan
Xan

Reputation: 77571

You can represent your function as a string:

var f = function(){ /* do stuff */ }
chrome.tabs.executeScript(tab.id, {code: "("+f.toString()+")();"});

Be careful, the function still needs to be self-contained (not use any non-local variables), as it will be executed in a different context.

Upvotes: 2

Related Questions