0

I build an extension (my pet project) where I click on name of snippet and it will automatically add it to console. I'm stuck because when I use console.log my snippets is already "entered" and after invoking that function it shows reference error: enter image description here

The point is - how to write something into a console using event to "paste snippet" without hitting enter?

kelsny
  • 23,009
  • 3
  • 19
  • 48
  • 1
    Logging something to the console doesn't execute it. So logging a function definition doesn't define the function. – Barmar Apr 29 '22 at 17:48
  • If you want to execute it, use `eval()` – Barmar Apr 29 '22 at 17:50
  • You need to expose the following code in page context ([more info](/a/9517879)): `window.checkElemWidth = function checkElemWidth() { ..... }` instead of using console.log. – wOxxOm Apr 29 '22 at 18:03

1 Answers1

-1

You'll want to eval the output you're logging as well (but that can be very dangerous with uncontrolled input).

For example:

const testFunctionText = `var test = () => console.log(1)`

console.log(testFunctionText)
eval(testFunctionText)

document.getElementById("run").onclick = () => {
    eval(document.getElementById("input").value)
}
<input id="input" placeholder="Evaluate console statement (no input on StackOverflow)">
<button id="run">Run</button>

With this code snippet, try putting test() into the provided input.

LeoDog896
  • 3,472
  • 1
  • 15
  • 40