wener
wener

Reputation: 7740

What does javascript:Function syntax mean?

Check here

javascript:Function("alert('this is ok')")();

same as

new Function("alert('this is ok')")();

What the syntax called ?

Any reference ?

EDIT

Sorry, my fault,it's only a label,and it's not equals new.

<script>
    javascript:C("val");
    wener:C("val");
    function C(v)
    {
        this.val = v;
        alert(window.val)
    }
</script>
<a href="javascript: alert('foo');">click me</a>

For <a href="javascript: alert('foo');">click me</a> see URI_scheme(Thanks apsillers) and draft-hoehrmann-javascript-scheme

Upvotes: 2

Views: 101

Answers (3)

apsillers
apsillers

Reputation: 115910

When you specify a fully qualified link, the text to the left of the colon is called the scheme.

<a href="https://example.com/foo">foo</a>
           ^ scheme is "https"

Browsers allow you the specify a scheme of javascript in HTML markup, in which case the browser interprets the link content to the right of the colon as a script to be executed, instead of a destination resource.

<a href="javascript:alert('I am a script, formatted as a link!')">foo</a>
            ^ scheme is "javascript"

(Please, never do this; use addEventListener("click", function() { ... }) instead.)

If you include the javascript: prefix in non-link contexts, however, it's interpreted as a JavaScript label. This is totally unnecessary.

Upvotes: 1

suff trek
suff trek

Reputation: 39767

This approach might be used when you want to execute JavaScript in browser's address bar. Copy/paste javascript:Function("alert('this is ok')")(); into browser's address bar and hit Enter.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160170

It's called "the old way of using JavaScript in attributes," relevant only in HTML.

You can also write:

poop:Function("alert('ohai')")();

Your example is just JavaScript code, not an HTML attribute, so it's just a label.

Upvotes: 5

Related Questions