Retrieve GTM code from database and display in angularJS app - javascript

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/

Related

Blazor server javascript not inserting elements as an MVC app would

I'm facing a little challenge here.
I'm trying to implement ads in my blazor server solution, and i cannot get it to work. So i've come up with a small MVC app where it works.
I must say that the blazor app is for a client i'm working for, and I don't know who supplies these adds. They send the code that i must implement for it to work.
Here is the stuff that they have asked me to implement in the head of the webpage
<script type="text/javascript">
var utag_data = {
}
</script>
<!-- Loading script asynchronously -->
<script type="text/javascript">
(function(a,b,c,d){
a='//partnerurl';
b=document;c='script';d=b.createElement(c);d.src=a;d.type='text/java'+c;d.async=true;
a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a);
})();
</script>
<script async='async' src='https://macro.adnami.io/macro/spec/adsm.macro.someId.js'></script>
<script>
var adsmtag = adsmtag || {};
adsmtag.cmd = adsmtag.cmd || [];
</script>
<link rel="preconnect" href="https://cdn.cookielaw.org">
<link rel="preload" href="https://cdn.cookielaw.org/consent/tcf.stub.js" as="script"/>
<script src="https://cdn.cookielaw.org/consent/tcf.stub.js" type="text/javascript" charset="UTF-8"></script>
<link rel="preconnect" href="https://securepubads.g.doubleclick.net">
<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script>
var googletag = window.googletag || {};
googletag.cmd = googletag.cmd || [];
window.yb_configuration = {"domain":"clientdomain"};
(function (y, i, e, l, d, b, I, R, D) {
d.Yieldbird = d.Yieldbird || {};
d.Yieldbird.cmd = d.Yieldbird.cmd || [];
l.cmd.push(function () {l.pubads().disableInitialLoad();});
b = i.createElement('script'); b.async = true;
b.src = (e === 'https:' ? 'https:' : 'http:') + '//jscdn.yieldbird.com/' + y + '/yb.js';
I = i.getElementsByTagName('script')[0];
(I.parentNode || i.head).insertBefore(b, I);
})('950dff97-bb8d-4667-952b-d72ce8bbe88b', document, document.location.protocol, googletag, window);
</script>
<script>
googletag.cmd.push(function () {
googletag.pubads().enableLazyLoad({
fetchMarginPercent: 150,
renderMarginPercent: 75,
mobileScaling: 1.5
});
});
</script>
And for each add placement i've received some html/javascript i must place at the location.
Heres an example:
<!-- /x,y/domain/domain.dk/billboard_1 -->
<script async="async" src="https://securepubads.g.doubleclick.net/tag/js/gpt.js">
</script>
<script>
var googletag = googletag || {};googletag.cmd = googletag.cmd || [];
</script>
<script>
googletag.cmd.push(
function() {
var YBmapping = googletag.sizeMapping().addSize([931,0],[[930,180]]).addSize([0,0],[]).build();
googletag.defineSlot('/x,y/domain/domain.dk/billboard_1', [[930, 180]], 'div-gpt-ad-billboard_1').defineSizeMapping(YBmapping).addService(googletag.pubads());
googletag.enableServices();
});
</script>
<div id='div-gpt-ad-billboard_1'>
<script>
googletag.cmd.push(function() {
googletag.display('div-gpt-ad-billboard_1');});
</script>
</div>
I've obfuscted some variables. But i guess you get the hang of it..
This is from the MVC app, and it works. It places extra html inside my div with the div-gpt-ad-billboard_1 id. So on the website the HTML would look like this:
<div id="div-gpt-ad-billboard_1">
<script>
googletag.cmd.push(function() {
googletag.display('div-gpt-ad-billboard_1');});
</script>
<div id="google_ads_iframe_/x,y/domain/domain.dk/billboard_1_0__container__" style="border: 0pt none; width: 930px; height: 0px;"></div></div>
And if i deploy my MVC app to the live endpoint we have, an iFrame is inserted into the div with the google_ads_iframe Id, where the add is displayed.
Now on my blazor app, this doesn't happen.
I've created a blazor component which contains the ad i want to place. It looks like this:
<script async="async" suppress-error="BL9992" src="https://securepubads.g.doubleclick.net/tag/js/gpt.js">
</script>
<script suppress-error="BL9992">
var googletag = googletag || {};googletag.cmd = googletag.cmd || [];
</script>
<script suppress-error="BL9992">
googletag.cmd.push(
function() {
var YBmapping = googletag.sizeMapping().addSize([931,0],[[930,180]]).addSize([0,0],[]).build();
googletag.defineSlot('x,y/domain/domain.dk/billboard_1', [[930, 180]], 'div-gpt-ad-billboard_1').defineSizeMapping(YBmapping).addService(googletag.pubads());
googletag.enableServices();
console.log(googletag);
});
</script>
<div id='div-gpt-ad-billboard_1'>
<script suppress-error="BL9992">
googletag.cmd.push(function() {
googletag.display('div-gpt-ad-billboard_1');});
</script>
</div>
As i understand it you cannot directly call script tags in blazor components, but they work if you add the suppress-error, and i can atleast get it to console log from them.
The head is the same in the blazor app as in the MVC app, as script tag works fine in _Host.cshtml in blazor.
The issue is that for my blazor app the ad component looks like this on the live endpoint:
<div id="div-gpt-ad-billboard_1"><script><!--!-->
googletag.cmd.push(function() { googletag.display('div-gpt-ad-billboard_1');});
</script></div>
Notice that the entire div with the google iframe ID is missing. It's as if it doesn't update anything. I've tried to call statehaschanged from OnInitializedAsync. Nothing happens, and i guess it makes sense, since nothing is probably added to the render tree that statehaschanged activates the rerendering of.
Does anyone have any idea, how i can get it to work like the MVC app ?

How can I use Google Analytics code in React JS app?

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.

Google Tag Manager and $ (JQuery) undefined

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

Creating a dynamic popup for Disqus comments for different threads

Edit: It seems Disqus is using the current page URL as the comment thread identifier despite me being explicit and stating:
<script type="text/javascript">
var disqus_developer = 1;
var disqus_identifier = "#Model.UniqueThreadIdentifier"; <--- HERE
var disqus_shortname = 'foo';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
Read below for more details.
Disqus says that I can identify a "page" with a unique identifier.
Now in this particular page there are about 10 items and I'd like each item to have a personal Disqus discussion thread.
So here's the actual page that gets loaded:
#foreach (var strong in Model.StrongAgainst)
{
<div class="pick">
<div class="actions">
<a href="#modalDialogue" data-toggle="modal"
id="#strong.UniqueThreadIdentifier" class="btn btn-comment">
<i class="icon-comment"></i>
999
</a>
</div>
</div>
</div>
}
That #UniqueThreadIdentifier is what I'm using to let Disqus load the appropriate thread.
Next, in that same HTML view, I have this Javascript line, which using the UniqueIdentifier returns a PartialView with the appropriate Disqus configuration and HTML:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$(document).on("click", "#strong-against .pick .data .actions .btn-comment", function () {
var commentUniqueVar = $(this).attr("id");
$.ajax({
url: '/Counterpicks/GetCommentThread',
data: { uniqueidentifier: commentUniqueVar },
success: function (data) {
$('#strongAgainstCommentModal').html(data);
alert("Finished loading.");
}
});
});
});
</script>
And up to here it's 100% confirmed that the right values are being loaded into the HTML.
Here is the PartialView:
<div class="modal-body">
<div id="disqus_thread">
</div>
<script type="text/javascript">
var disqus_developer = 1;
var disqus_identifier = "#Model.UniqueThreadIdentifier";
var disqus_shortname = 'foobar';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>
Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments
powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">
Disqus</span></a>
</div>
Notice how I set the disqus_identifier using a strongly typed model with the correct value.
My only guess is that when declaring a variable like that, it's created globally? (I think?) And the Disque javascript library is always going to use the first value I assigned to it. Correct?
How can I appropriately load the correct identifier to the Disqus javascript library?
What the identifier allows you to do is display the same thread on multiple URLs, but you can't display multiple threads on the same URL using a new identifier alone (this is a common misconception). We developed a method for reloading a thread with AJAX called Disqus.Reset, which is documented here: http://docs.disqus.com/help/85/
You can also hack it without Disqus.Reset, and that's demonstrated on this post: http://collaborable.com/blog/disqus-jquery-hack-awesome-ux

javascript script is hidden in source view

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

Categories

Resources