Pseudo protocol JavaScript in JavaScript: use discussion

  • 2020-03-30 03:33:31
  • OfStack

The way to add javascript code to the client is to place it in the URL after the pseudo-protocol descriptor javascript:. This particular 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 more than one statement, you must separate those statements with a semicolon. The URL looks like this:


javascript:var now = new Date(); "<h1>The time is:</h1>" + now;

When the browser loads such a URL, it executes the javascript code contained in the URL and displays 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 to look exactly like any other document loaded into the browser.

Javascript urls can also contain javascript statements that perform only actions but do not return values. Such as:


javascript:alert("hello world!")

When this 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 doesn't change the document currently displayed. To do this, you must ensure that the last statement in the URL does not return a value. One way is to use void operator explicitly put the return value is specified for underfined, need only in javascript: void 0 at the end of the URL to use statements; Can. 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 the URL has no void operator, the return value of the window.open() method is converted to a string and displayed, and the current window is overwritten by the document shown below.


Related articles: