Where should analytics script be put in a React app? - javascript

Barion Pixel requires to put in code in my React app. When I put it in App.js or index.js, it raise an error. Do you have any idea where to put it? In index.html inhas no effect. Strange.
https://docs.barion.com/Implementing_the_Base_Barion_Pixel
<script>
// Create BP element on the window
window["bp"] = window["bp"] || function () {
(window["bp"].q = window["bp"].q || []).push(arguments);
};
window["bp"].l = 1 * new Date();
// Insert a script tag on the top of the head to load bp.js
scriptElement = document.createElement("script");
firstScript = document.getElementsByTagName("script")[0];
scriptElement.async = true;
scriptElement.src = 'https://pixel.barion.com/bp.js';
firstScript.parentNode.insertBefore(scriptElement, firstScript);
// Send init event
bp('init', 'addBarionPixelId', 'BP-0000000000-00');
</script>
I just show how error looks like:

You can try using dangerouslySetInnerHTML:
<script
dangerouslySetInnerHTML={{
__html: `
// Create BP element on the window
window["bp"] = window["bp"] || function () {
(window["bp"].q = window["bp"].q || []).push(arguments);
};
window["bp"].l = 1 * new Date();
// Insert a script tag on the top of the head to load bp.js
scriptElement = document.createElement("script");
firstScript = document.getElementsByTagName("script")[0];
scriptElement.async = true;
scriptElement.src = 'https://pixel.barion.com/bp.js';
firstScript.parentNode.insertBefore(scriptElement, firstScript);
// Send init event
bp('init', 'addBarionPixelId', 'BP-0000000000-00');`
}}
/>

Related

Include Javascript inside JS file

How can we include javascript link inside .js file?. .js file support include, require or import like CSS or PHP?
My Code :
// Global site tag (gtag.js) - Google Analytics
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.googletagmanager.com/gtag/js?id=UA-51600743-15';
document.body.appendChild(script);
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-51600743-15');
// Microsoft Clarity
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "9zvbjor3bn");
//Start of Tawk.to Script
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/61d019a4c82c976b71c45176/1foae8bkm';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
I am trying to add all tracking code inside one file analytic.js and adding that to my website so it will be easy for me to maintain in future, so i do not need to edit in every page whenever any changes required in tracking codes.
What is the correct way to include another js file inside js file?
async src="https://www.googletagmanager.com/gtag/js?id=UA-51600743-15";
//OR
require("https://www.googletagmanager.com/gtag/js?id=UA-51600743-15"};
//OR
import from "https://www.googletagmanager.com/gtag/js?id=UA-51600743-15";
//Or any other way?
Guide : https://www.geeksforgeeks.org/how-to-include-a-javascript-file-in-another-javascript-file/
Solution :
function include(file) {
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
script.defer = true;
document.getElementsByTagName('head').item(0).appendChild(script);
}
/* Include Many js files */
include('https://example.com/example.js');

Check is external Javascript has changed or not

Here is my code which might not be the best solution of my problem, and my goal is to check the external script (script.js) every 2 seconds if it's code has changed. If it is changed, then execute it.
function connectLoader(retval) {
console.log('Executing...');
var old = document.getElementById("EPMagic");
if (old !== null) {
old.outerHTML = "";
delete old;
}
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute('id','EPMagic');
script.setAttribute('type','text/javascript');
script.setAttribute('src','http://server.com/script.js');
head.appendChild(script);
}
setInterval('connectLoader()',2000);
The problem is that /script.js is still executed even if it is not being changed.
The code on /script.js is simply alert('Execute');
Use setAttribue to set the attributes values:
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute('id','loadScript');
script.setAttribute('type','text/javascript');
script.setAttribute('src','http://server.ip/script.js');
head.appendChild(script);

Why the dynamic script does not execute?

the code in the dynamic script does not execute:
var script = document.createElement('div')
script.innerHTML = `<script>alert('asd')<\/script>`
document.body.appendChild(script)
while the code below works:
var div = document.createElement('div')
var script = document.createElement('script')
script.text = `alert('asd')`
div.appendChild(script)
document.body.appendChild(div)
what the different and why?

Why Can't I get my google maps to update lat/lng on button click?

I am trying to get my center location to change on my google map based on a button click. I have more functionality to add later, but I can't get this basic update to work. I have a default value that loads on page load. The button should set a new location, but I see that it does update but then is quickly overridden by the default value because the page loads again.
I am new to google maps, and I am just trying to figure out how to load and interact with the map correctly.
Here is my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var deanLat = 43.0843816;
var deanLong = -89.5302394;
var deanAddress = '1277 deming way, madison wi';
var stmaryLat = 43.0592730;
var stmaryLong = -89.4015130;
var stmaryAddress = '700 S Park St, Madison, WI 53715';
$("#FindDean").click(function() {
refreshMap(deanLat, deanLong);
});
function alertme(message) {
alert (message);
}
function refreshMap(ilat,ilong) {
ilat = typeof ilat !== 'undefined' ? ilat : stmaryLat;
ilong = typeof ilong !== 'undefined' ? ilong : stmaryLong;
alertme(ilat);
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(ilat, ilong)
};
gmap = new google.maps.Map(document.getElementById('mapholder'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=true&callback=refreshMap';
document.body.appendChild(script);
}
window.onload = loadScript;
When you run $(#FindDean) the DOM has not yet rendered (the onload event hasn't fired), so the element with id="FindDean" can't be found.
Move this:
$("#FindDean").click(function() {
refreshMap(deanLat, deanLong);
});
Inside the onload function:
function loadScript() {
$("#FindDean").click(function() {
refreshMap(deanLat, deanLong);
});
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=true&callback=refreshMap';
document.body.appendChild(script);
}
window.onload = loadScript;
working fiddle

How do I add a javascript alert to innerHTML at runtime

When a particular event happens that I listen out for - I want to populate the div 'divDynamicAdvert` with the javascript that calls my Google Ad code.
Huge thanks to "tenbits" for showing me that I need to be appending a script node like this:
function myEventHandler(evt) //called when event is caught
{
var script = document.createElement('script');
script.textContent = 'alert(1)';
document.getElementById('divDynamicAdvert').appendChild(script);
}
This works great, but in place of the alert, I need to insert the Google Ads Javascript:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-3286208413631803";
/* Standard MPU */
google_ad_slot = "8630273973";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
I've tried:
var script = document.createElement('script');
script.textContent = 'google_ad_client = 'ca-pub-3286208413631803'; google_ad_slot = '8630273973'; google_ad_width = 300; google_ad_height = 250;';
document.getElementById('divDynamicAdvert').appendChild(script);
var script = document.createElement('script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"');
document.getElementById('divDynamicAdvert').appendChild(script);
I've tried escaping the slashes too, but no luck... Can you guys help?
As #slebetman already said, innerHTML wont work. If you trying to evaluate script via DOM, and not eval(code), etc - do this with SCRIPT Node:
var script = document.createElement('script');
script.textContent = 'alert(1)';
document.getElementById('divDynamicAdvert').appendChild(script);
// actually it doesnt matter where you append it
EDIT:
In any case create a SCRIPT NODE, and then manipulate with it - add a script content to it OR add src attribute if you reference external source
var script;
// content
script = document.createElement('script')
script.textContent = 'alert(1)'
document.body.appendChild(script);
// google api source
script = document.createElement('script');
script.src = 'ANY_URL';
// -> in this case, same as script.setAttribute('src', 'ANY_URL');
document.body.appendChild(script);
Having some further questions, do not hesitate to ask in comments.

Categories

Resources