How to use a variable in a function expression which is injected in a page?

Posted by anonymous on Stack Overflow See other posts from Stack Overflow or by anonymous
Published on 2012-12-11T22:18:46Z Indexed on 2012/12/12 17:04 UTC
Read the original article Hit count: 131

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: Building a Chrome Extension - Inject code in a page using a Content script

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about google-chrome-extension