Why the dynamic script does not execute? - javascript

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?

Related

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

Where should analytics script be put in a React app?

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');`
}}
/>

Appending script to HTML via JS

I am trying to add run an external script that basically appends HTML elements to the page. I can't just use a script tag as I need it to run asynchronously, however when I use <script async src="..."> the script appends the elements to the bottom of the page, rather than the class that it's being called in.
Therefor I've created this script to append the external script tag to the page.
var x = document.createElement("SCRIPT");
x.src = '//rss.bloople.net/?url=https%3A%2F%2Fwww.coindesk.com%2Ffeed%2F&limit=5&showicon=true&type=js';
var newsContainer = document.createElement("div");
newsContainer.className = "newsContainer";
newsContainer.innerHTML = x;
document.getElementById("newsContainerId").appendChild(newsContainer);
This doesn't work however, as it appends this to the page
[object HTMLScriptElement]
Change newsContainer.innerHTML = x;
To
newsContainer.appendChild(x);
var x = document.createElement("SCRIPT");
x.src = '//rss.bloople.net/?url=https%3A%2F%2Fwww.coindesk.com%2Ffeed%2F&limit=5&showicon=true&type=js';
var newsContainer = document.createElement("div");
newsContainer.className = "newsContainer";
newsContainer.appendChild(x);
document.getElementById("newsContainerId").appendChild(newsContainer);
//
<div id="newsContainerId">Container</div>
The issue occurs here:
newsContainer.innerHTML = x;
xis evaluated - which you can't really do on this object. You should use x.innerHTML do make it do what you'd expect. Just x by itself is described by JavaScript as [object HTMLScriptElement] and that is what gets added to your newsContainer.
Try skipping this shoving around in the first place and add the element x to newscontainer:
var x = document.createElement("SCRIPT");
x.src = '//rss.bloople.net/?url=https%3A%2F%2Fwww.coindesk.com%2Ffeed%2F&limit=5&showicon=true&type=js';
var newsContainer = document.createElement("div");
newsContainer.className = "newsContainer";
newsContainer.appendChild(x);
document.getElementById("newsContainerId").appendChild(newsContainer);

How to restrict calling js appending functionality twice

I need to append the css and js file dynamically and am using below method
document.getElementsByTagName('head')[0].appendChild();
this method doesn't allow second parameter.
I have to append both the css and js file dynamically. I am calling the above method twice to append the files. Any other generic way to restrict the above method to be called only once.
Here it is what i have tried:
var jscss = function(cp, sp){
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", cp);
document.getElementsByTagName('head')[0].appendChild(css);
var script = document.createElement('script');
script.src = sp;
document.getElementsByTagName('head')[0].appendChild(script);
};
jscss();
Well, I think you can achieve it by providing id to the element and before appending it just check if that element exists.
Example:
var jscss = function(cp, sp){
if(!document.getElementById("customStyleSheet")){
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("id", "customStyleSheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", cp);
document.getElementsByTagName('head')[0].appendChild(css);
}
if(!document.getElementById("customScript")){
var script = document.createElement('script');
script.src = sp;
script.id = "customScript";
document.getElementsByTagName('head')[0].appendChild(script);
}
};
jscss();
Hope this will help you :)
You could use a documentfragment in order to only need to call to appendChild once to add both elements:
var jscss = function(cp, sp){
var fragment = document.createDocumentFragment();
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", cp);
fragment.appendChild(css);
//Does not affect the DOM
var script = document.createElement('script');
script.src = sp;
fragment.appendChild(script);
//Does not affect the DOM
document.getElementsByTagName('head')[0].appendChild(fragment);
//Adds both elements to the DOM
};
jscss();
Use a variable to remember if the function has run already.
var jscss_run = false;
function jscss(cp, sp) {
if (jscss_run) {
return; // don't run a second time
}
jscss_run = true;
// do all the real work
}

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