Inserting script/div chatbot in GTM - javascript

I'm having problems using faqbot.
The normal way of installing it is simple :
before the closing body tag insert this (i changed the keys in this example):
<script type="application/javascript">
var FAQBOT = {
PUBLIC_KEY: "0000000000000000",
AUTO_OPEN: 500
}
</script>
<div id="faqbot-00000000"></div>
<script src="https://faqbot.co/public/js/bundle.js"></script>
This works like a charm.
Now I want to do this using GTM, i'm positive my tag fires (on the DOM Rdy).
I first tried to just put the code inside the custom html tag because that should be a code injector on itself.. this didnt work..
Then I used the DOM Manipulation to achieve it and indeed when i check the source of my page, the tags are right there , BUT the bot doesn't work..
<script>
window.onload = function() {
var s = document.createElement('script');
s.type = 'application/javascript';
var code = 'var FAQBOT = { PUBLIC_KEY:"0000000000000000000",AUTO_OPEN: 500 }';
var d = document.createElement('div');
d.id ='faqbot-00000000';
var s2 = document.createElement('script');
s2.src = 'https://faqbot.co/public/js/bundle.js';
try {
s.appendChild(document.createTextNode(code));
document.body.appendChild(s);
} catch (e) {
s.text = code;
document.body.appendChild(s);
}
document.body.appendChild(d);
document.body.appendChild(s2);
}
</script>
Why is this not working , does it fire too late ?

I tried to put the following code in a custom HTML tag:
<script type="application/javascript">
var FAQBOT = {
PUBLIC_KEY: "0000000000000000",
AUTO_OPEN: 500
}
</script>
<div id="faqbot-00000000"></div>
<script src="https://faqbot.co/public/js/bundle.js"></script>
using this custom event as a trigger:
gtm.dom
and it seems to work properly:
Request URL: https://faqbot.co/public/js/bundle.js
Request Method: GET
Status Code: 200 OK

Related

Add external JS script through code

I'm trying to implement a map widget from 'Awesome Table' in the source code of an open-source CRM.
The piece of code I have to add is
<div data-type="AwesomeTableView" data-viewID="-KLtnY5OHJPgnEOX1bKf"></div>
<script type="text/javascript" src="https://awesome-table.com/AwesomeTableInclude.js"></script>
I try to do it with jQuery like this :
$(document).ready(function () {
var div = "<div data-type=\"AwesomeTableView\" data-viewID=\"-KLtnY5OHJPgnEOX1bKf\"></div>";
var scr = "<script type=\"text/javascript\" src=\"https://awesome-table.com/AwesomeTableInclude.js\"></script>";
$("body").append(div, scr);
});
But I got a problem : in the console the src appears like this:
http://127.0.0.1/edsa-EspoCRM-4.1.6/api/v1/https://awesome-table.com/AwesomeTableInclude.js
See what's wrong...
Before I tried with javascript but I had an almost identical result (nothing appeared and the script didn't worked)
var div = document.createElement("div");
div.id = "lacarte";
div.dataset.type = "AwesomeTableView";
div.dataset.viewid = "-KLtnY5OHJPgnEOX1bKf";
div.style.height = "200px";
var scr = document.createElement("script");
scr.type = "text/javascript";
scr.src = "https://awesome-table.com/AwesomeTableInclude.js";
var page = document.getElementById("content");
page.appendChild(div);
page.appendChild(scr);
If you have any idea?
You should use $.getScript to load and execute scripts dynamically.
And if your script is a prerequisite for your div, you can use the callback executed when the script is loaded end executed, to append the div.
Here is the documentation: http://api.jquery.com/jQuery.getScript/
$(document).ready(function () {
$.getScript("https://awesome-table.com/AwesomeTableInclude.js", function (data, textStatus, jqxhr) {
var div = '<div data-type="AwesomeTableView" data-viewID="-KLtnY5OHJPgnEOX1bKf"></div>';
$("body").append(div);
});
});
You have to escape the slashes in the script src, type and closing of the script /:
$(document).ready(function () {
var div = '<div data-type="AwesomeTableView" data-viewID="-KLtnY5OHJPgnEOX1bKf"></div>';
var scr = '<script type="text\/javascript" src="https:\/\/awesome-table.com\/AwesomeTableInclude.js"><\/script>';
$("body").append(div, scr);
});
The following code adds the two elements exactly as shown.
function byId(id){return document.getElementById(id);}
function newEl(tag){return document.createElement(tag);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var div = newEl('div');
div.setAttribute('data-type', 'AwesomeTableView');
div.setAttribute('data-viewID', '-KLtnY5OHJPgnEOX1bKf');
var script = newEl('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'https://awesome-table.com/AwesomeTableInclude.js');
document.body.appendChild(div);
document.body.appendChild(script);
}
The resulting source is: https://awesome-table.com/AwesomeTableInclude.js
As seen here:
<body>
<div data-type="AwesomeTableView" data-viewid="-KLtnY5OHJPgnEOX1bKf"></div><script type="text/javascript" src="https://awesome-table.com/AwesomeTableInclude.js"></script>
</body>

How javascript detects where the function is defined, top/bottom?

I have the below code is working as long as I load the employee section and its scripts as part of the index.html
index.html Working Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Employee Details loaded as usual and sript is executing able to see alert</h1>
</body>
</html>
Script.js
var empModule = (function (empModule) {
var Years = null;
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
return {
empModule: empModule
}
} (empModule || {}));
Error Scenario:
We decide to move employee related section based on some condition. Hence we are loading this section and section related script(emp.js) via Ajax. But now it is throwing the error empModule.viewModel is not a constructor. Why is it so?
If I move the document.ready section at the bottom like the below order, it is working
Emp.js(moved from script.js to emp.js and load via ajax(
var empModule = (function (empModule) {
var Years = null;
// Code not working when we load this script file using Ajax.
// But works if we move this document.ready at bottom
//$(document).ready(function () {
// var empdata = { Name: 'Billa' }
// var myVM = new empModule.viewModel(empdata);
//});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
//Working only if I keep the ready section here
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
return {
empModule: empModule
}
} (empModule || {}));
The function empModule will get executed automatically as it is self
executing function. When it is executing it needs to prepare a
empModule.viewModel object, but failed to do that when viewModel
definition is located after document.ready (caller). This happens only
when I load this script via Ajax, but works if I pre load it in a page
This is because in the first example the script.js is part of the document and therefore the document.ready waits for that .js file to be loaded before trying to call empModule.viewModel().
In the second example, your script is loaded asyncronously, but the page is not taking this into account. So the page loads (without the script.js) and then you load the script.
At this point, the document is ready (as the ajax loaded script isn't part of the document) so the empModule.viewModel() call fires straight away, before the rest of the script (which is the bit that defines the function) and you get your error.
Just like #dougajmcdonald said is your issue, but your solution is, instead of loadding by AJAX, just insert the script tag in your document:
// Instead of $.ajax(... /myScript.js) use:
function loadMyScript(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'myScript.js';
script.onload = function() {
empModule.doSomething(); // or callback
};
}

Dynamically loaded jQuery not defined when using inline script

Situation:
jQuery is dynamically loaded together with other scripts by one file javascripts.js in the <head> section of the html file
Each html file has it's own javascript code executed on jQuery(document).ready() in the <body> section of the html file
Problem:
Error: jQuery is not defined for javascript in the <body> section
Modifying the html file is not an option (+1000 files with same problem)
Example html file:
<html>
<head>
<title>JS test</title>
<script src="javascripts.js" type="text/javascript"></script>
</head>
<body>
<input type="text" class="date">
<script>
jQuery(document).ready(function() { // Error: jQuery not defined
jQuery('.date').datepicker();
});
</script>
</body>
</html>
javascripts.js:
// Load jQuery before any other javascript file
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
console.log("state: "+state);
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('javascripts/jquery-1.8.3.min.js', function() {
var files = Array(
'javascripts/functions.js',
'javascripts/settings.js'
);
if (document.getElementsByTagName && document.createElement) {
var head = document.getElementsByTagName('head')[0];
for (i = 0; i < files.length; i++) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', files[i]);
script.async = true;
head.appendChild(script);
}
}
});
This is happening, as many in the comments have pointed out, because you are loading jQuery asynchronously. Asynchronous means the rest of the code is executed, and so your document-ready handler (DRH) line is running before jQuery is present in the environment.
Here's a really hacky way of resolving this. It involves making a temporary substitute of jQuery whose job is just to log the DRH callbacks until jQuery has arrived. When it does, we pass them in turn to jQuery.
JS:
//temporary jQuery substitute - just log incoming DRH callbacks
function jQuery(func) {
if (func) drh_callbacks.push(func);
return {ready: function(func) { drh_callbacks.push(func); }};
};
var $ = jQuery, drh_callbacks = [];
//asynchronously load jQuery
setTimeout(function() {
var scr = document.createElement('script');
scr.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js';
document.head.appendChild(scr);
scr.onload = function() {
$.each(drh_callbacks, function(i, func) { $(func); });
};
}, 2000);
HTML:
jQuery(document).ready(function() { alert('jQuery has loaded!'); });
Fiddle: http://jsfiddle.net/y7aE3/
Note in this example drh_callbacks is global, which is obviously bad. Ideally hook it onto a namespace or something, e.g. mynamespace.drh_callbacks.
I believe this simple solution should do the trick. The changed line in the html changes the jquery onload function to a regular function. The jquery onload function will sometimes happen before the jquery is loaded and we can't have that. It's unreliable. We need that function not to execute on page load, but AFTER the jquery has loaded.
To that end, the three lines I've added in the javascript.js are inside the code that is executed immediately after jQuery has finished loading. They test to see if the pageLoaded function has been defined (so you don't have to put one on every page, only the ones that need it) and then execute it if it's there.
Now, because the change to the HTML is simple, you can just do a regex search and replace on those 1000 files to fix them. Tools like Sublime, Eclipse or TextPad are suited for that task.
Cheers!
Example html file:
<html>
<head>
<title>JS test</title>
<script src="javascripts.js" type="text/javascript"></script>
</head>
<body>
<input type="text" class="date">
<script>
function pageLoaded() { // changed
jQuery('.date').datepicker();
} // changed
</script>
</body>
</html>
javascripts.js:
// Load jQuery before any other javascript file
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
console.log("state: "+state);
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('javascripts/jquery-1.8.3.min.js', function() {
var files = Array(
'javascripts/functions.js',
'javascripts/settings.js'
);
if (document.getElementsByTagName && document.createElement) {
var head = document.getElementsByTagName('head')[0];
for (i = 0; i < files.length; i++) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', files[i]);
script.async = true;
head.appendChild(script);
}
}
if( typeof(pageLoaded) == "function" ){ // added
pageLoaded(); // added
} // added
});
You should try following workaround to load scripts synchronously:
function loadJS(src, callback) {
document.write('<scr'+'ipt src="'+src+'"><\/scr'+'ipt>');
callback();
}
IMPORTANT to note: this function should be called always before DOM is fully rendered.

Appending Jquery in HTML dynamically

I am new to jquery. I am trying to append Jquery in an HTML page in java. To include jquery.js file I have written following code:
scriptTag += "var script = document.createElement('script');" +
"script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'; " +
"script.type = 'text/javascript'; " +
"document.getElementsByTagName('head')[0].appendChild(script);" +
and then I appended following js+jquery code with it
"var script2 = document.createElement('script'); window.onload = function() {" +
"$(document).ready(function() {" +
"$(\"#identity\").hide();});};" +
"script2.type = 'text/javascript'; " +
"document.getElementsByTagName('head')[0].appendChild(script2);";
So basically I am trying to write this :
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var script2 = document.createElement('script');
window.onload = function() {
$(document).ready(function() {
$("#identity").hide();
});
};
script2.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script2);
What I want to do is that I want my function after window load. Somehow, writing $(document).ready(function() { alone does'nt work. I get an error that $ is not defined (looks like jquery.js is not ready yet).
To avoid this problem I have used window.onload = function() {. But now I am getting error: $(document).ready is not a function. I am really confused here on how to write this thing. Is this the correct approach? Any help/guidance is highly appreciated.
[Edit]
Please note that the following code (without jquery) works fine:
window.onload = function() {
document.getElementById('identity').style.visibility='hidden';
};
[Edit]
Actually I am making a web proxy, where I download page and serve them with custom look and field. The pages does not contain any jquery files nor can I include or write HTML. I can only add my Js dynamically using java etc.
Here is some code that shows how to load a script file dynamically and also delay calling of $(document).ready until that file is loaded:
http://jqfaq.com/how-to-load-java-script-files-dynamically/
The code you use to load jquery.min.js file is called asycnhroniously. Probably this file has not been loaded at the moment you try to execute jquery function.
Therefore you should make sure that the file is loaded using a callback function.
In the following link you can find an example on how to this:
http://blog.logiclabz.com/javascript/dynamically-loading-javascript-file-with-callback-event-handlers.aspx
Also here is a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>index</title>
<script type="text/javascript">
function loadScript(sScriptSrc, callbackfunction) {
//gets document head element
var oHead = document.getElementsByTagName('head')[0];
if (oHead) {
//creates a new script tag
var oScript = document.createElement('script');
//adds src and type attribute to script tag
oScript.setAttribute('src', sScriptSrc);
oScript.setAttribute('type', 'text/javascript');
//calling a function after the js is loaded (IE)
var loadFunction = function() {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
callbackfunction();
}
};
oScript.onreadystatechange = loadFunction;
//calling a function after the js is loaded (Firefox)
oScript.onload = callbackfunction;
//append the script tag to document head element
oHead.appendChild(oScript);
}
}
var SuccessCallback = function() {
$("#identity").hide();
}
window.onload = function() {
loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', SuccessCallback)
};
</script>
</head>
<body>
<span id="identity"> This text will be hidden after SuccessCallback </span>
</body>
You should use this code in your scriptTag variable and then you can use eval() function to evaluate the script in this variable. Also you can load the second javascript file in the callback function using jquery's getscript function

how can i load <script>'s into an iframe?

I've got the logic working to append into my iframe from the parent
this works:
$('#iframe').load(function() {
$(this).contents().find('#target').append('this text has been inserted into the iframe by jquery');
});
this doesn't
$('#iframe').load(function() {
$(this).contents().find('body').append('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>');
});
.lf
The problem is something to do with the inserted script tags not being escaped properly.
Half of the javascript is becomes visible in the html, like the first script tag has been abruptly ended.
Maybe the error is with your string, never create a string in javascript with a literal < /script> in it.
$('#iframe').load(function() {
$(this).contents().find('body').append('<scr' + 'ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></scr' + 'ipt>');
});
I'm a bit surprised that isn't working [Edit: No longer surprised at all, see mtrovo's answer.]...but here's what I do, which is mostly non-jQuery per your comment below but still quite brief:
var rawframe = document.getElementById('theframe');
var framedoc = rawframe.contentDocument;
if (!framedoc && rawframe.contentWindow) {
framedoc = rawframe.contentWindow.document;
}
var script = doc.createElement('script');
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js";
framedoc.body.appendChild(script);
Off-topic: I really wouldn't give an iframe (or anything else) the ID "iframe". That just feels like it's asking for trouble (IE has namespace issues, and while I'm not aware of it confusing tag names and IDs, I wouldn't be completely shocked). I've used "theframe" above instead.
Warning: loading script in this manner would make scripts running in main window context
i.e.: if you use window from somescript.js, it would be NOT iframe's window!
$('#iframe').load(function() {
$(this).contents().find('body').append('<scr' + 'ipt type="text/javascript" src="somescript.js"></scr' + 'ipt>');
});
To be able to use iframe context inject script with this:
function insertScript(doc, target, src, callback) {
var s = doc.createElement("script");
s.type = "text/javascript";
if(callback) {
if (s.readyState){ //IE
s.onreadystatechange = function(){
if (s.readyState == "loaded" ||
s.readyState == "complete"){
s.onreadystatechange = null;
callback();
}
};
} else { //Others
s.onload = function(){
callback();
};
}
}
s.src = src;
target.appendChild(s);
}
var elFrame = document.getElementById('#iframe');
$(elFrame).load(function(){
var context = this.contentDocument;
var frameHead = context.getElementsByTagName('head').item(0);
insertScript(context, frameHead, '/js/somescript.js');
}

Categories

Resources