views:

271

answers:

3

I'm trying to include the Google Website Optimizer JavaScript code, below, in a Zope3 page template. It's used for for A/B testing.

However, the template html parser, which I believe is the standard Python HTMLParser module, throws the following error:

raise PTRuntimeError(str(self._v_errors))
- Warning: Compilation failed
- Warning: <class 'HTMLParser.HTMLParseError'>: bad end tag: u"</sc'+'ript>", at line 45, column 44
PTRuntimeError: ['Compilation failed', '<class \'HTMLParser.HTMLParseError\'>: bad end tag: u"</sc\'+\'ript>", at line 45, column 44']

As I see it I have two options:

  • Rewrite the code so it passes (my JS-foo is weak, no idea where to start).

  • Make HTMLParser ignore the code. I've tried CDATA tags with no success. I've also tried putting the js in an external file and linking to it, but this seems to break the optimizer functionality.

The suspect code:

<!-- Google Website Optimizer Control Script -->
<script>
<![CDATA[
function utmx_section(){}function utmx(){}
(function(){var k='1010538027',d=document,l=d.location,c=d.cookie;function f(n){
if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.indexOf(';',i);return c.substring(i+n.
length+1,j<0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;
d.write('<sc'+'ript src="'+
'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com'
+'/siteopt.js?v=1&utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='
+new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
'" type="text/javascript" charset="utf-8"></sc'+'ript>')})();
]]>
</script><script>utmx("url",'A/B');</script>
<!-- End of Google Website Optimizer Control Script -->
+1  A: 

Given the parser's weakness, you could try breaking up the parts of the CDATA that it's trying to interpret as tags, e.g. where you now have </sc'+'ript>' try <'+'/sc'+'ript>' etc (+ does string catenation in JS, just like in Python, so it will put back together again the tags you break up this way, just like the tags that are already broken up in the original).

If that keeps giving parse errors, lose the CDATA and change every < into &lt;, every > into &gt; -- not sure if JS will handle that but it's worth a try... good luck!

Alex Martelli
A: 

My guess is the parser doesn't like the fact that

</sc'+'ript>

is split in two. Which is perfectly valid javascript but may confuse the htmlparser?

Might want to try

<'+'/sc'+'ript>'
Ryu
Just as valid as Alex's answer - but he added a bit more detail ;)
Jon Hadley
A: 

One other option you have is to place the code in an external file and reference it instead of embedding it directly into the code. I've done this and it works well. That's always an easier way if you don't want the validator to crawl any javascript or css.

Online Colleges Geek
@Online Colleges Geek - See my OP, I tried this and it 'broke the optimizer functionality'.
Jon Hadley