문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top