I never seen this before but you can invoke the HREF attribute of a link using javascript if the HREF contains javascript:;//code……;
On my example below click on both links. they do the same thing even though they have different javascript in the HREF.
for example:
<script type="text/javascript">
function clickme()
{
var link = document.getElementById("clickme");
eval(link.href);
}
</script>
<a id="clickme" href="javascript:alert('hello');">I will alert hello</a>
<br />
<a href="javascript:clickme()">click me</a>
I tested this on IE8, Firefox 3.6.8, Safari 5.0.1, and Chrome 6.0.472.55. Is this standardized, so I will not have to worry about this feature being deprecated in the future?
You don’t have to worry about it being deprecated in the future. It’s a bad idea now.
What’s really happening there is this: There’s a link using the
javascript:protocol, which is respected by browsers. It means that everything following thejavascript:is JavaScript and should be executed by the JS interpreter.When you retrieve the link’s href, you receive it as a string, e.g. “javascript:clickme()”. You can use
evalon strings to execute JavaScript. Now, you’d think that would fail (because of thejavascript:protocol thing at the front), but it doesn’t, because JavaScript has labels and that looks like a label when you treat it as JavaScript code.So it works, but it’s a bad idea. It’s also disallowed (because of the
eval) in the new “strict” mode of the latest version of JavaScript, ECMAScript 5th edition.In general, when we think we need to use
evalfor something, it indicates that there’s a problem with our code and that some refactoring is in order. The exceptions to that rule are very edgey edge cases that most of us will never run into. In this case, rather than having thehrefattribute contain the code that we want to execute, it should just use the code we want to execute. Your example, for instance, has aclickMefunction as the only thing being used. Rather thanevaling it, we should just call that function directly.