javascript: URLs
Warning:
Using javascript:
URLs on the web is discouraged as it may lead to execution of arbitrary code, similar to the ramifications of using eval()
. It may also reduce accessibility because it deviates from normal link behavior.
JavaScript URLs, URLs prefixed with the javascript:
scheme, are used as fake navigation targets that execute JavaScript when the browser attempts to navigate. If the URL evaluates to a string, it is treated as HTML and rendered by the browser.
Syntax
JavaScript URLs start with the javascript:
scheme and are followed by JavaScript code. The code will be parsed as a script.
javascript:
In this example, the href
attribute of an element is set to a
javascript:
URL that navigates to a new page with the content "Hello, world!":
Click me
Note that because javascript:
URLs do not create history entries, there's no way to go back to the previous page without refreshing.
Using javascript:
URLs as form actions
In this example, the action
attribute of a element is set to a
javascript:
URL that alerts a message when submitted:
Instead of doing this, consider listening for the form's submit
event and handling it with JavaScript:
Using javascript:
URLs as iframe sources
In this example, the src
attribute of an element is set to a
javascript:
URL that navigates to a new page with the content "Hello, world!":
Instead of doing this, consider setting the srcdoc
attribute instead:
Using javascript:
URLs with window.location
In this example, the window.location
property is set to a javascript:
URL that navigates to a new page with the content "Hello, world!":
window.location = "javascript:'Hello world!'";
Instead of doing this, consider using DOM APIs to modify the page content. For example:
document.body.textContent = "Hello, world!";
Specifications
Specification |
---|
HTML # the-javascript:-url-special-case |