Jan Idar Hoversholm Jan Idar Hoversholm - 2 months ago 28
Javascript Question

Stop prompt() redirecting to input

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>

Now, when I press cancel on the prompt it redirects to 'null'. If I press OK it redirects to the text input.

How do I stop ALL redirects from this? Like, both cancel and OK.


Assuming you actually want to use JavaScript within a link such as with a bookmarklet:

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.

You probably don't want to use JavaScript within a link:

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>