I'm trying to execute an event listener using eval()
["document.addEventListener('load', "].forEach(f => {
eval(f + `function(){ console.log("test") })`)
})
The console never logs however. When I replace eval() with console.log, it shows that the string has correct syntax
["document.addEventListener('load', "].forEach(f => {
console.log(f + 'function(){ console.log("test") })');
}) // logs 'document.addEventListener('load', function(){ console.log("test") })'
So if the syntax is correct, what's the problem?
When I remove 'function()' from the string and just directly fire 'console.log', it works.
["document.addEventListener('load', "].forEach(f => {
eval(f + 'console.log("nice"))');
}) // this works
'document.addEventListener('load', console.log("nice"))', so since you are directly executingconsole.log("nice"), it executes it (thats when it prints), but then adds the event handler becomes undefined