Is it possible to pass an anonymous function or a reference to the executeScript function?

Is it possible to pass an anonymous function to execX chrome API call? I currently 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 to execute as a function reference and not a string? I know the file parameter, but I would rather just pass the reference to the function already provided in bg.js. I don't like the line because I am losing the syntax highlighting / formatting in my editor, among other reasons.

+3


source to share


1 answer


You can think of your function as a string:

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

      



Be careful, the function must still be self-contained (don't use any non-local variables) as it will execute in a different context.

+2


source







All Articles