I want to use below Google Analytics code in my react JS app in the script tag.
When I put the below code in Helmet I showing a syntax error?
How Can I use it?
<script>
(function (w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
"gtm.start": new Date().getTime(),
event: "gtm.js",
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", "GTM-Code");
</script>
<!-- End Google Tag Manager -->
<!-- Makes it possible to add onclick attribute to buttons and such -->
<script>
window.onload = function () {
var anchors = document.getElementsByTagName("*");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function () {
code = this.getAttribute("whenClicked");
eval(code);
};
}
};
</script>
Simply do below two steps, Copy the code below and paste it onto every page of your test environment.
Paste this code as high in the head of the page as possible:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->
Additionally, paste this code immediately after the opening body tag:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
As per the provided source code, you didn't add noscript tag after the body tag.
Please provide exact error you are having to get more understanding of
the issue.
You could try using a 3rd party library such as React GA that handles script injection for you.
Related
I'm using Google Tag Manager. If I hit F12 and enter jQuery, jQuery is defined and working. However, $ is not. It appears that the Tag Manager is redefining $.
Any ideas please?
Here's a cut down example.
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Google Tag Manager -->
<script>
(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({
'gtm.start':
new Date().getTime(), event: 'gtm.js'
}); var f = d.getElementsByTagName(s)[0],
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-ABCDEFG');
</script>
<!-- END OF Google Tag Manager script -->
<title></title>
</head>
<body>
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-ABCDEFG"></iframe></noscript>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</body>
</html>
Order in imports count, as the script run as soon as it's <scrit> element is loaded.
one solution is to move your gtm script from the head to after Jquery.
Second solution is to add defer attribute to the gmt script. Defer will force the script to wait the page to load before starting the execution
Dynamically change the src tag
I am integrating Google analytics into my Angular app. It requires to add a google tracking id in the script-src and later. It needs to load at first before anything else.
While it works fine for one env, I wanted to have different Ids for different enviorment.
I am trying something like:
<script>
var googleTrackingId;
switch (window.location.hostname) {
case 'mycompany.com':
googleTrackingId = 'UA-123123-3'; // production
break;
case 'staging.mycompany.com':
googleTrackingId = 'UA-123123-2'; // staging
break;
default:
googleTrackingId = 'UA-123123-1'; // localhost
}
</script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${googleTrackingId}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', googleTrackingId);
</script>
But the src tag is not changing.
You can find the desired tracking ID based on hostname first, then create the <script> tag.
<script>
var googleTrackingId;
switch (window.location.hostname) {
case 'mycompany.com':
googleTrackingId = 'UA-123123-3'; // production
break;
case 'staging.mycompany.com':
googleTrackingId = 'UA-123123-2'; // staging
break;
default:
googleTrackingId = 'UA-123123-1'; // localhost
}
document.write( '<scr' + 'ipt async src="https://www.googletagmanager.com/gtag/js?id=' + googleTrackingId + '"></scr' + 'ipt>' );
</script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', googleTrackingId);
</script>
Using Javascript, you can get the <script> element by ID, and append whatever you want to the element's src attribute.
Edit: You can alter the script element immediately when it is loaded, using the script's onload event handler:
var analyticsScript = document.getElementById('analytics');
analyticsScript.onload = function() {
analyticsScript.src += '?id=3wrwerf45r3t36y645y4';
console.log(analyticsScript.src);
}
<script src='https://some_source' id="analytics"></script>
Why your approach does not work
In your HTML code, you are trying to use template literals here:
<script async src="https://www.googletagmanager.com/gtag/js?id=${googleTrackingId}"></script>
However, template literals work in Javascript, not in HTML (at least not to my knowledge). Also, template literals are wrapped inside backticks (`), not double quotes (") !
I have a few dynamic values which I get inside the body tag only. Now when I try to push those values using dataLayer object using 'script' tag and prepend it to the head section, it does not work.
Here is the code -
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var JS = document.createElement('script');
<!-- Google Tag Manager -->
var tagManagerSnippet = '(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({"gtm.start":\n' +
'new Date().getTime(),event:"gtm.js"});var f=d.getElementsByTagName(s)[0],\n' +
'j=d.createElement(s),dl=l!="dataLayer"?"&l="+l:"";j.async=false;j.src=\n' +
'"https://www.googletagmanager.com/gtm.js?id="+i+dl;f.parentNode.insertBefore(j,f);\n' +
'})(window,document,"script","dataLayer","GTM-XXXXXXXX");\n';
<!-- End Google Tag Manager -->
JS.text = tagManagerSnippet;
head.prepend(JS);
var code = 'dataLayer = [];\n' +
'dataLayer.push({"eventLabel" : "Interested in Science"});\n' +
'dataLayer.push({"eventLabel" : "Interested in IT"});\n';
JS.text = code;
head.prepend(JS);
</script>
I can see that the above code properly executes and append the JS in the head section. However, the Tag does not fire. And when I simply put the above code in the head section (not on the fly) it runs as expected.
I have several websites that use an AngularJS app. Each website has different GTM tracking. I'm storing the tracking code in our database. Eg:
<!-- Google Tag Manager -->
<noscript>
<iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<script>
(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({
'gtm.start':
new Date().getTime(), event: 'gtm.js'
}); var f = d.getElementsByTagName(s)[0],
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
'//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-XXXXX');</script>
<!-- End Google Tag Manager -->
In my angular app, I've retrieved the code, but how do I go about inserting it into my HTML?
I tried:
<div id="tracking">
{{tracking}}
</div>
but this displays the code on the screen.
this may help you
instead of
<div id="tracking">
{{tracking}}
</div>
you write that
<div ng-bind-html="tracking">
</div>
in script you must do
<script src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script>
and inject in the module
var app = angular.module('myApp', ['ngSanitize']);
It seems that the solution is to use the $sce service. Example here: http://erikaugust.com/thoughts/ng-bind-html/
Why don't the script tags and content appear inside a div tag for example.
I have the following code:
<div>
<!-- BEGIN: YTV Syndicate script -->
<!-- Edit Section-->
<script type="text/javascript">
alert('hello!'); //check if scripts actually works
var YTVSYND = {}
YTVSYND.key = 'xxx';
YTVSYND.template = {}
YTVSYND.template.name = 'ytv'
YTVSYND.template.size = 'size300x250'
YTVSYND.soc = '<%= Model.Code %>';
YTVSYND.type = 'career';
</script>
<!-- END: EDIT -->
<!-- === DO NOT EDIT BELOW=== -->
<script type="text/javascript">
var ytvSyndUrl = (location.protocol == 'https:') ? 'https://' : 'http://';
ytvSyndUrl += 'syncdn.youniversitytv.com/synapi/embed/ytv-embed-api.js';
ytvSyndUrl = "/Scripts/ytv-embed-api.js"
var str = "<scr" + "ipt type='text/javascript' src='" + ytvSyndUrl + "'>";
str += "<";
str += "\/scr" + "ipt>";
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = ytvSyndUrl;
$("#fgm").html(str)
</script>
<!-- EOF: YTV Syndicate script -->
</div>
It executes just but when I check the source it only shows the comments
<!-- BEGIN: YTV Syndicate script -->
<!-- Edit Section-->
<!-- END: EDIT -->
<!-- === DO NOT EDIT BELOW=== -->
<!-- EOF: YTV Syndicate script -->
and no sign of the script tags and the actual script .
Note: this is inside a jquery modal, i have the same script inside a normal page and it shows up in the source view.
1st
2nd
When you load some HTML content into the DOM dynamically with jQuery, it strips out the <script> tags completely. Under most circumstances it evaluates them (with "eval()" which is more-or-less what the browser would do), but they don't remain available in the DOM.
You can see the code in the jQuery source starting around this point.
edit — note that I'm assuming that you're adding some HTML dynamically. If you were not doing that, then the <script> tags would be in the DOM, and you would be able to see them in Firebug, etc.
View source is not your solution
view dom is you solution
use web developer of firebug