1

Assume I do the following:

  const
    externalVal = 'something',
    fn = () => {
      console.log(externalVal)
    })

  console.log(fn.toString())

The console log will stringify the function and specifically, console.log(externalVal) will be stringified.

Is there any way I can get the function block to convert to a string but contain the value of externalVal so it would come out like: console.log('something')?

The reason being is I can't access the pages window object via a browser extension content script, but I can inject a script into the document and run it - this doesn't help much unless I can pass in the value as well.

Just to clarify, I know I can access the the window object by injecting the script. That's the purpose of this question because I need to pass a value into that script and converting the function to a string isn't eval'ing the value of the variable.

webnoob
  • 15,747
  • 13
  • 83
  • 165
  • 1
    But you **can** access `window` object of the page, see [this](/a/9517879) and [another example](/a/46870005). – wOxxOm Sep 10 '19 at 13:16
  • @wOxxOm Well that's what I'm trying to do - insert a script into the page but for me, unless I can insert one of the values from my current context when the function is stringified it doesn't help – webnoob Sep 10 '19 at 13:19
  • I doubt you will be able to do that. Time to figure out a different way of doing whatever you are trying to do. – epascarello Sep 10 '19 at 13:19
  • @epascarello Yes, I doubt it too but thought it worth a question :) – webnoob Sep 10 '19 at 13:21
  • That being said, I've just thought of a work around. I could pass in my function which uses DOM messaging between that and the content script to *ask* for the value. – webnoob Sep 10 '19 at 13:23
  • 1
    If you run via textContent you can "pass" the arguments in the same string e.g. assuming fn = function(arg1, arg2) {} the code would be scriptElement.textContent = \`(${fn})(${JSON.stringify(['foo', 'bar']).slice(1, -1)})\` – wOxxOm Sep 10 '19 at 13:30
  • Brilliant! Thanks. Please add the answer and I'll give you some points ;) – webnoob Sep 10 '19 at 13:36

0 Answers0