javascript: Pseudo-Protocol

Contact Us or call 1-877-932-8228
javascript: Pseudo-Protocol

javascript: Pseudo-Protocol

Try this:

  1. Open your browser.
  2. In the location bar, type in javascript:alert("Hello world!"); like so:
  3. Press Enter.

You should get an alert reading "Hello world!". The javascript: prefix is called a pseudo-protocol, because it mimics the protocol syntax (e.g, like http:, ftp:, and mailto:). It provides an easy way to test JavaScript on a page. It can also be used in links as in the demo below:

Code Sample:

JavaScriptBasics/Demos/psuedo-protocol.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Pseudo-Protocol</title>
</head>
<body>
<p><a href="javascript:alert('Hello world!');">Say hello</a></p>
</body>
</html>

When the user clicks the link, the JavaScript alert will execute.

This is generally considered a bad practice. The preferred way to handle this is to use the href attribute to provide an alternative page in case JavaScript is not enabled. You could provide a generic page with a "JavaScript is required" message or, even better, you could provide a page that accomplishes the same task as the alert as in the following the demo:

Code Sample:

JavaScriptBasics/Demos/better-than-psuedo-protocol.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Better than Pseudo-Protocol</title>
</head>
<body>
<p><a href="hello-world.html" onclick="alert('Hello world!'); return false;">Say hello</a></p>
</body>
</html>

When the user clicks the link...

  • If JavaScript is enabled, the alert pops up and the return false; statement explicitly cancels the link's default behavior.
  • If JavaScript is NOT enabled, the link takes the user to hello-world.html.
Next