首页 > 解决方案 > 如何删除 html 中的脚本标签

问题描述

我正在尝试删除 html 中的这个脚本标签,它用于谷歌分析,我希望在使用不接受 cookie 时删除这个脚本。

<script>     
var _gaq = _gaq || [];
         _gaq.push(['_setAccount', 'UA-46776072-1']);
         _gaq.push(['_setDomainName', 'av.gov.mk']);
         _gaq.push(['_trackPageview']);

        (function () {
             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);
         })();
     };
</script>

标签: javascripthtmlgoogle-analytics

解决方案


将 GA 脚本放入接受 cookie 后将调用的函数中。

function startGA(source) {
  document.getElementById(window.event.srcElement.id).style.display = "none";
  alert("Google Analytics script will be rendered now!")
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-46776072-1']);
  _gaq.push(['_setDomainName', 'av.gov.mk']);
  _gaq.push(['_trackPageview']);

  (function() {
    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);
  })();
}
<input type="button" id="acceptCookies" value="Accept Cookies" onclick="startGA(this)" />


推荐阅读