Home >Web Front-end >JS Tutorial >Pseudo-protocol in JavaScript javascript: usage discussion_javascript skills
The way to add javascript code to the client is to place it in the URL after the pseudo-protocol specifier javascript:. This special protocol type declares that the body of the URL is arbitrary JavaScript code, which is run by the JavaScript interpreter. If the javascript code in the javascript:URL contains multiple statements, these statements must be separated by semicolons. Such a URL looks like this:
javascript:var now = new Date(); "<h1>The time is:</h1>" + now;
When the browser loads such a URL, it will execute the javascript code contained in the URL and display the string value of the last javascript statement as the content of the new document. This string value can contain HTML markup and be formatted so that it appears exactly like any other document loaded into the browser.
javascript URL can also contain javascript statements that only perform actions but do not return values. For example:
javascript:alert("hello world!")
When this kind of URL is loaded, the browser only executes the javascript code in it, but since there is no value to display as a new document, it does not change the currently displayed document.
Usually we want to use javascript:URL to execute some javascript code that does not change the currently displayed document. To do this, you must ensure that the last statement in the URL does not return a value. One way is to use the void operator to explicitly specify the return value as underfined. Just use the statement void 0; at the end of the javascript:URL. For example: The following URL will open a new, empty browser window without changing the contents of the current window:
javascript:window.open("about:blank"); void 0;
If this URL does not have a void operator, the return value of the window.open() method will be converted into a string and displayed, and the current window will be overwritten by the document as shown below.