How do I add a javascript alert to innerHTML at runtime - javascript

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.

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);

load javascript files from folder

I am not sure what is the best approach to load all .js files from a folder from within index.html
The number of .js files will change so I cannot define them in the index.html the usual way. I cannot use php or jQuery solutions which would make it easier.
<script>
var count = 1;
function LoadNext()
{
var newScript = document.createElement("script");
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", "page-" + count++ + ".js"); //Increment the counter so we get the next page each time
newScript.onload = LoadNext; //When the script loads call this function again
document.getElementsByTagName("head")[0].appendChild(newScript)
}
LoadNext();
</script>
You can load a new JS file by creating a new <script> tag.
var filename = "JSDir/JSFile.js";
var newScript = document.createElement("script"); ///Create a new <script> element
newScript.setAttribute("type", "text/javascript"); // Set type to JS
newScript.setAttribute("src", filename); //Set src, your file to load
document.getElementsByTagName("head")[0].appendChild(newScript) //Append this script tag to the end of your head element
If you know your JS files are going to be named basename-1.js you can set a callback so that onload you increment to the next fielname basename-2.js 3, 4... and when the final one fails to load it will stop trying to load further.
var count = 1;
function LoadNext()
{
var newScript = document.createElement("script");
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", "basename-" + count++ + ".js"); //Increment the counter so we get the next page each time
newScript.onload = LoadNext; //When the script loads call this function again
document.getElementsByTagName("head")[0].appendChild(newScript)
}
LoadNext(); //Load basename-1.js
^^Not tested, but if that way of checking the file exists fails. You can always use AJAX and check for 404

Changing innerHTML of script tags in IE for loading google plusone button explicitly

To add Google's plusone button on your website the following script tag is to be inserted (for explicit load).
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{"parsetags": "explicit"}
</script>
It looks pretty straight forward in HTML. However I wan't to insert the script using a JS file. So I use the following code:
var e = document.createElement('script');
e.src = "https://apis.google.com/js/plusone.js";
e.id = "googplusonescript";
e.innerHTML = '{"parsetags": "explicit"}';
document.getElementsByTagName("head")[0].appendChild(e);
It works pretty awesome in all the browsers except IE because IE doesn't allow us to write the innerHTML of script tags. Anywork arounds anyone ? (I have jquery inserted in the page. So can use jquery too.)
Came across the same issue.
Under IE you should use
script.text = '{"parsetags": "explicit"}';
instead of script.innerHTML
try creating a textNode and appending it to your script tags:
var myText = document.createTextNode('{"parsetags": "explicit"}');
myScriptTag.appendChild(myText);
Try the following:
window['___gcfg'] = { parsetags: 'explicit' };
var ispoloaded;
function showpo() {
var pohd = document.getElementsByTagName('head')[0];
var poscr = document.createElement('script');
poscr.type ='text/javascript';
poscr.async = true;
poscr.text ='{"parsetags": "explicit"}'; //works on IE too
poscr.src = "http://apis.google.com/js/plusone.js";
pohd.appendChild(poscr);
ispoloaded = setInterval(function () {
//check if plusone.js is loaded
if(typeof gapi == 'object') {
//break the checking interval if loaded
clearInterval(ispoloaded);
//render the button, if passed id does not exists it renders all plus one buttons on page
gapi.plusone.go("idthatexists");
}
}, 100); //checks every 0.1 second
}

Multiple jQ.src in Bookmarklet

This is my current bookmarklet code.
if (1 == 1) {
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.onload=runthis;
jQ.src = 'http://www.domain.com/jquery-1.5.2.min.js';
document.head.appendChild(jQ);
}
I want to call multiple jQ.src. I tried this however it doesn't work on some sites.
This is my current bookmarklet code.
if (1 == 1) {
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.onload=runthis;
jQ.src = 'http://www.domain.com/jquery.js';
jQ.src = 'http://www.domain.com/jquery2.js';
document.head.appendChild(jQ);
}
On some sites it works and other it doesn't Any insight?
Thanks!
Are you sure that works on some sites? I think you're just getting lucky and picking up the site's already loaded jQuery.
Anyway, if you want to add two JavaScript files then you'll have to append two script tags:
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jquery.js';
document.head.appendChild(jQ);
jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jquery2.js';
jQ.onload = runthis;
document.head.appendChild(jQ);
Also note that the onload is only on the second one since you presumably need both JavaScript files loaded before runthis will work.
If you're loading jQuery, you might want to check if the page has loaded it already:
var jQ;
if(typeof window.jQuery != 'function') {
// jQuery isn't there yet so load it up.
jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jquery.js';
document.head.appendChild(jQ);
}
jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src = 'http://www.domain.com/jQuery2.js';
jQ.onload = runthis;
document.head.appendChild(jQ);
Adding a jQuery.noConflict() call might be a good idea too, the page might be using $ for something else so forcing it to be jQuery could break the page.

Categories

Resources