December 14, 1999 - The javascript: Protocol | WebReference

December 14, 1999 - The javascript: Protocol

Yehuda Shiran December 14, 1999
The javascript: Protocol
Tips: December 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

You are probably familiar with the basic protocols, such as http: and ftp:. JavaScript-enabled browsers support the javascript: protocol, which lets you execute statements rather than loading a new document. For example, enter the following URL in your browser:

javascript:alert("Hello World")

Now enter a two-statement URL:

javascript:alert("Hello World");alert("Hello Net")

As you can see, it is possible to enter multiple statements after the preceding javascript: specification. Also note that a semicolon is not necessary after the last statement in the URL. Entering a javascript: URL in the browser's Location bar is almost useless. However, we can implement javascript: URLs in various browser elements. The most trivial implementation is a simple link:

<A HREF="javascript:alert('Hello World')">Hello Word</A>

Simply click the following link, and an alert box will appear: Hello World. If it doesn't work, make sure JavaScript is currently enabled in your browser. Notice the alternation of quotes. Since the HREF attribute requires quotes, we must make sure the internal javascript: URL doesn't use the same type of quotes. In the preceding example, we use double quotes for the HTML attribute, and single quotes for the JavaScript statement.

The JavaScript statement used in a javascript: URL should not return any value. For example, the alert() method doesn't return a value; in other words, it returns undefined. If the statement returns undefined, the browser simply executes it. However, if it returns an explicit value, the browser loads a new page, with the javascript: URL in the Location bar, and the returned value in the body of the page.

When taking advantage of the javascript: protocol, we must make sure the statement doesn't return any value. Therefore, we need to apply the void operator if the statement returns an actual value. Here's an example:

<A HREF="javascript:void(str='Doc JavaScript')">

The void operator evaluates its expression, and returns undefined. The parentheses surrounding the expression are optional, but they are important when writing compact, one-line scripts. If you're not sure if a statement returns a value, use the void operator to stay on the safe side. When inserting several statements in a single javascript: URL, all value-returning statements require a void operator. Take a look at the following example:

<A HREF="javascript:void(a=1);void(b=prompt('Enter a number:','99'))">

Note that the entire javascript: URL should be as compact as possible. Long javascript: URLs tend to generate errors or crash the browser. We suggest that you stick to a maximum of about 500 characters.

For more information on the javascript: protocol, refer to Column 35, Bookmarklets.