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.
views:
15answers:
2yes, you can run statements in url box.
like this:
javascript:if(2>1){alert('2 > 1');}
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 your browser, 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.
You can read more about void
in another answer I gave a while ago: http://stackoverflow.com/questions/2863878/help-me-understand-javascriptvoidnull/2864019#2864019.