Re: Javascript within href reported as error if contains & or =

Please ensure that responses get sent to the list, rather than just me.

Peter Jones wrote:
> <a href="javascript:myfunc('fred&barney are great!');">test</a>
> Thanks.  I understand that URLs must be checked this way.   I just disagree
> that javascript within a href should be checked the same way.

You just fail to understand how HTML works.  The HTML parser doesn't 
change its parsing rules based upon the URI scheme.  &amp; is the 
correct way to encode ampersands in HTML because "&" is a special 

Rather than objecting to fixing the error because you don't think it's 
right or don't think it will work, you should accept that it is right 
and when you fix it, you will see that it actually does work.

Here's a simple way to prove that it works:

<a href="javascript:alert('fred&amp;barney are great!');">test</a>

Put that link in a page and click it.  You will get an alert that says 
"fred&barney".  You will not, as you seem to think, get 
"fred&amp;barney" because the &amp; is decoded by the HTML parser before 
it gets passed to the JavaScript engine.

The fact that it works without using &amp; is due to error handling in 
browsers' HTML parsers.

>  What says that fred&barney is a url?  Since it follows the protocol directive
> 'javascript', clearly it isn't.

It's still a URI!  It makes no difference whether it's http:, ftp: or 
anything else.

> [...] What I'm left with is, maybe:
> <a href="javascript:void(0);" onclick="myfunc('fred&barney are great!');
> return false;">test</a>

Even then, you would have to encode the ampersand as &amp; to be valid.

> In this case, the validator is dictating how I should code.  That's not it's
> job.

It's job is to tell you what mistakes you have made, and it does that 
reasonably well.  Your job is to learn and understand why they are 
mistakes and then fix those mistakes, not argue with about things you 
don't understand.

> It's to tell me if I have legit code.  After the javascript protocol
> definition in the href, the Javascript spec tells me what is legit.

No, again, you just fail to understand the issue.

Lachlan Hunt

Received on Friday, 13 April 2007 13:18:09 UTC