For some reason I cannot find an answer to this, so here I am.
So, in my Java EE application I have this:
<a href="javascript:prompt('Make sure the text is selected,
then press either CTRL+C or right click and then \'Copy\'.', '{PASS}');" class="btn btn-success btn-md" role="button">{CHARS} Chars</a>
The javascript:
protocol has a hidden feature. If a value other than undefined
is passed to it, it will be interpreted as a string and (essentially) passed to document.write
to build a new HTML document.
You can test this out by seeing what javascript:null
and javascript:'<!DOCTYPE html><title>Hello</title> World!'
do in links.
The fix for this particular issue is to make sure you never return anything to javascript:
, which is why you will often see javascript:void(0)
in links.
Rather than polluting your markup with unmaintainable JavaScript, put your script in a JavaScript file where it belongs. Also, since your link isn't being used to target a new document, use a <button>
with some styles:
document.querySelector('#example').addEventListener('click', function () {
console.log('do stuff');
}, false);
<button type="button" id="example">{CHARS} Chars</button>