Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove <script> tags using jQuery

I want to remove this Google Analytics block, using jQuery.

<script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
    try {
        //var pageTracker = _gat._getTracker("xxx");
        pageTracker._trackPageview();
    } catch(err) {}
</script>

THE REASON

Because I am creating a bespoke screen reader convertor for jQuery based on a client specification. It's the Google Analytics that is bugging me.

THE PROBLEM

It works with .remove() until you navigate away, then press back. Google Analytics hangs.

like image 393
Barrie Reader Avatar asked Jun 21 '10 14:06

Barrie Reader


2 Answers

Try this:

var replacementDoneIn = $(document.body).text(); //remove Google Analytics document.write line
        var regExMatch = /document\.write\(unescape/g;
        var replaceWith = "//document.write";
        var resultSet = replacementDoneIn.replace(regExMatch, replaceWith);
        $("body").html(resultSet);

Hope that helps!

like image 116
Ryano Avatar answered Oct 12 '22 15:10

Ryano


You can also hook document.write and check if its google anlytics code before stopping it like this:

<script>
// Must run before google analytics though
old_document_write = document.write;
document.write = function(str)
{
     if(/* determine if the str is google analyic code */)
         return false; // dont write it
     else
        old_document_write(str);
}
</script>
like image 23
Christopher Tarquini Avatar answered Oct 12 '22 13:10

Christopher Tarquini