I'm trying to inject a function into a webpage via Chrome extension content script by:
function inject(code) {
    var actualCode = '(' + code + ')();';
    var script = document.createElement('script');
    script.textContent = actualCode;
    (document.head||document.documentElement).appendChild(script);
    script.parentNode.removeChild(script);
}
var myObj = person;  // myObj/person is passed in from elsewhere
var fn = function() {
    alert(myObj.name);
};
inject(fn); // myObj undefined
My issue is, since fn is a function expression, I can't pass in myObj.personName. So my question is, how can I construct a function expression that includes a variable? Do I do some sort of string concatenation instead?
I also tried to pass the object to the function, as follows:
function inject(code, myObj) {
    var actualCode = '(' + code + ')(' + myObj +');';
    ...
But this did not work, and caused a "Uncaught SyntaxError: Unexpected identifier" error.
Related: Insert code into the page context using a content script
 
     
     
     
    