简体   繁体   中英

Can I run arbitrary javascript code in the javascript:void() function using the browser's address bar?

我想知道是否可以通过URL框在javascript:void()函数中运行代码块(包括for循环和if语句)。

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) .

yes, you can run statements in url box.

like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM