1

I was wondering if I could run a block of code(which includes for loops and if statements) in a javascript:void() function through the URL box.

2 Answers 2

3

void isn't a function, it's an operator. This means you can use it with or without parenthesis. All it does is makes the expression following it return undefined. In the case of navigation, returning undefined prevents the result of the expression from causing navigation away from the page.

You can run any JavaScript code through the address bar of some browsers, whether you use the void operator or not. void just makes it safe to do so without navigating away. A popular alternative to void is to wrap your code in a self executing anonymous function:

javascript:(function () { alert("hello"); })();

Often, snippets of code like this are saved as a bookmark so that they can be run at the click of a link in the bookmarks or favourites bar on any page. These snippets are referred to as Bookmarklets.

The javascript: protocol has been disabled for URL entry in some newer browsers, most notably Firefox (since 6.0). This is primarily to prevent users from being targets of self-XSS attacks, where they are convinced by a potential attacker to paste a javascript: URL in the address bar. In Google Chrome and recent versions of Internet Explorer, the javascript: part is stripped from the pasted code. These snippets still work as bookmarklets in all the above browsers, however.

You can read more about void in another answer I gave a while ago: Help me understand javascript:void(null).

Sign up to request clarification or add additional context in comments.

2 Comments

It won't work from the address bar (tested in IE 11 and Firefox 27.0.1). You have to save it as bookmark to make it work.
@Nolonar: I wasn't able to verify your comment for IE 11, since I'm away at the moment and only have Linux on my laptop. I spent about 10 minutes searching the web and can only find references that indicate the same behaviour as Chrome (where the javascript: protocol is stripped when pasted). I was able to verify this in Firefox, however. I've updated the answer with my findings.
0

yes, you can run statements in url box.

like this:

javascript:if(2>1){alert('2 > 1');}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.