Reputation: 1359
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
Upvotes: 1
Views: 273
Reputation: 586
Moved here because longer answer
You could try a function that takes the code string, and runs it immediately if the page is loaded otherwise add an event listener
function runWhenLoaded(codeString) {
if (document.readyState === 'complete') { // checks if it is loaded already
eval(codeString);
else {
document.addEventListener('load', () => eval(codeString));
}
}
Upvotes: 1