Suppose you had a website that performed a search function using JavaScript, and it got the user's search terms from URL parameters. The URL might look something like this:
Code:
https://example.com?query=this+is+what+i+want+to+search
And suppose the JavaScript handling the search used the eval function, it might look something like this:
Code:
var url = new URL(window.location.href)
var searchparam = url.searchParams.get('query')
var evalstring = "someobject.search('" + searchparam + "')"
eval(evalstring)
The query parameter "this is what i want to search" is fetched from the URL and inserted into the "evalstring" variable. It would look like this:
Code:
someobject.search('this is what i want to search')
That string is then passed to eval(). This would cause the someobject.search() function to execute on the search param.
However, imagine if the following URL was used:
Code:
https://example.com?query=search+this');alert('injected
When the query parameter gets inserted into evalstring, the final string will look like this:
Code:
someobject.search('search this');alert('injected')
When eval runs on this string, it will execute the search function, but will also pop up an alert box containing the string "injected". You could replace this alert function with any arbitrary JavaScript you want, and it would get executed by the browser. It could contain a keylogger, or a crypto miner - anything that can be implemented in JavaScript.
Now imagine someone tricked another user into clicking the link above with some malicious JavaScript payload. The user would load the page and immediately execute whatever JavaScript the attacker cooked up for them. That's why it's dangerous to use the eval() function, especially with user input.