javascriptpythonzopegoogle-website-optimizerzpt

Validating Google Optimizer javascript code via HTMLParser


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:

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

Solution

  • 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!