在Javascript函数中插入Google再营销代码

时间:2015-11-11 11:34:17

标签: javascript

我正在尝试将Google再营销代码插入CookieCuttr的Javascript函数中,以阻止Cookie。

我使用CookieCuttr代码来阻止cookie,功能如下:

<script>
function cookiestart(){
[ ... ]
}

if (jQuery.cookie('cc_cookie_accept') == 'cc_cookie_accept') {

HERE GOES THE GOOGLE ANALYTICS CODE

}
</script>

这非常有效:Google Analytics Cookie会被阻止,直到访问者接受它们为止。 现在,我必须加入......

<script>
[...]
</script>

...部分Google再营销代码:

<!-- Google Code per il tag di remarketing -->
<!--------------------------------------------------
I tag di remarketing possono non essere associati a informazioni di     identificazione personale o inseriti in pagine relative a categorie sensibili.     Ulteriori informazioni e istruzioni su come impostare il tag sono disponibili     alla pagina: http://google.com/ads/remarketingsetup
--------------------------------------------------->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 123456789;
var google_custom_params = window.google_tag_params;
var google_remarketing_only = true;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//googleads.g.doubleclick.net/pagead/viewthroughconversion/123456789/?value=0&amp;guid=ON&amp;script=0"/>
</div>
</noscript>

有没有办法在前一个代码中包含此代码?

谢谢大家。

1 个答案:

答案 0 :(得分:0)

这应该做你需要的。在调用代码时,这一点并不明显,因此在文档加载之前等待添加分析代码。 这是基于Can I add javascript dynamically to an existing script element

中的答案
document.addEventListener("DOMContentLoaded", function() {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.appendChild(document.createTextNode("\
/* <![CDATA[ */\n\
var google_conversion_id = 123456789;\n\
var google_custom_params = window.google_tag_params;\n\
var google_remarketing_only = true;\n\
/* ]]> */\n\
"));
    document.body.appendChild(script);
    script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "//www.googleadservices.com/pagead/conversion.js");
    document.body.appendChild(script);
    var noscript = document.createElement("noscript");
    noscript.innerHTML =
'<div style="display:inline;">\
<img height="1" width="1" style="border-style:none;" alt="" src="//googleads.g.doubleclick.net/pagead/viewthroughconversion/123456789/?value=0&amp;guid=ON&amp;script=0"/>\n\
</div>';
    document.body.appendChild(noscript);
}, false);