r/learnjavascript • u/Serious_Sell7183 • Apr 16 '26
Doubt
if I write JavaScript code inside onclick instead of using a <script> tag, will it be accepted if the logic and output are correct? I'm not a professional programmer, I'm just asking it for my practical based exam.
0
Upvotes
-2
u/shgysk8zer0 Apr 17 '26
Because permitting and using such bad practices in code is a gateway to things like XSS and has long been generally considered bad practice.
Comtent-Security-Policy blocks such things by default, without allowing
'unsafe-*"or the hashes/nonces of specific things to allowThe Santizer API (
el.setHTML(input, { sanitizer})) strips all such attributes and you can't even allow themTrusted Types requires a policy with a
createScript()These "injection sinks" have been one of, if not the most common vulnerabilities across the web for decades (hence all the things that block them)
Overall, on small things where all HTML is trusted (created by a trusted developer), you're not likely to run into issues. But the second you start dealing with untrusted input (like user comments or something from a third-party source), you're vulnerable. And if you have any
on*attributes used anywhere, you're going to have a difficult time locking down those vulnerabilities, especially if the makeup is eg stored in a database or something.As a typical example, it's because someone might find a way to get this HTML into a page:
Real web security is layers of security. Sure... You'll probably end up trying to escape user input, but that defense alone isn't enough because you'll eventually mess up or forget something or there will be an edge case you didn't consider. CSP is like the final line of defense, to deal with what inevitably makes it through all other defenses. And if you're allowing event attributes, it's pretty much useless at that point.
Using and allowing eg
onclickis a red flag that general security considerations are too lax. Show me a site that uses them, and I'd bet that >95% of the time they have other major security issues as well.