Search code examples
javascriptxpathmoovwebtritium

Inject multi-line JS in Tritium


I have a javascript snippet that I need to inject on each page to fire off my google analytics. I tried using inject and keep getting errors:

inject("// load ga.js if it doesn't exist
    if (!window._gat) {
        var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? "https://ssl" : "http://www") + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s);
    };")

What is the best way to approach this problem with tritium?


Solution

  • The inject() function seems to convert the string to HTML and then place it into the current node. Since your string is JS, not valid HTML, all sorts of errors are thrown.

    Instead, you can use Tritium's insert_javascript() function, described in the docs at: http://tritium.io/current#XMLNode.insert_javascript(Text%20%25js).

    insert_javascript() also encloses the string in CDATA tags so you don't have to worry about HTML character encodings and such.

    Here's an example of how it could work in your case: http://tester.tritium.io/7532c4e18619051c5736a0ad990e4a33b1b3f00f