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
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).
2 Comments
javascript: protocol is stripped when pasted). I was able to verify this in Firefox, however. I've updated the answer with my findings.