How to insert special script into header? - javascript

I know how to insert a standard script to the body or header (changing .body or .header) depending on the case with:
document.body.appendChild(document.createElement('script')).src = 'https://url.com';
But I have a script that I need to insert into the header but it contains a var and Iā€™m not sure how I should insert it.
<script type="text/javascript"> var _iub = _iub || []; _iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; </script> <script type="text/javascript" src="//cdn.iubenda.com/cs/iubenda_cs.js" charset="UTF-8" async></script>
Any ideas?

You can create a script element and add the content with .innerHTML, afer just insert to body (or header).
var script = document.createElement('script');
script.innerHTML = ` var _iub = _iub || []; _iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; `;
document.body.appendChild(script);

Related

JavaScript - Remove script tags from HTML

When a HTML file is loaded, I want to run a script which would remove few scripts tags from the HTML file based on the user agent.
To do this I've followed this question: Removing all script tags from html with JS Regular Expression
But couldn't achieve what I needed, the script tags are removed and they are getting downloaded.
HTML:
<html>
<head>
</head>
<body>
<p></p>
<script type="text/javascript">
function stripScripts(s) {
var div = document.createElement('div');
div.innerHTML = s;
var scripts = div.getElementsByTagName('script');
var i = scripts.length;
while (i--) {
scripts[i].parentNode.removeChild(scripts[i]);
}
return div.innerHTML;
}
var userAgent = navigator.userAgent;
console.log(userAgent);
if (!userAgent.includes("Chrome")) {
stripScripts(); // Here how can I call the present index.html?
}
else {
var para = document.createElement("P");
var t = document.createTextNode("You cannot view this in Chrome");
para.appendChild(t);
document.body.appendChild(para);
};
</script>
<script type="text/javascript" src="scripts2.js"></script> <!-- load only when the condition is met else remove it --!>
</body>
</html>
When I run the index.html in chrome, script2.js is loading all the time.

Display complete Javascript tag in div

I need to place an entire javascript function in a div and show it for testing purposes, how can I accomplish this? I am doing this from code behind in asp.net
EDIT
<!-- Facebook Conversion Code for Website Purchase -->
<script type='text/javascript'>
(function() {
var _fbq = window._fbq || (window._fbq = []);
if (!_fbq.loaded) {
var fbds = document.createElement('script');
fbds.async = true;
fbds.src = '//connect.facebook.net/en_US/fbds.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(fbds, s);
_fbq.loaded = true;
}
})();
window._fbq = window._fbq || [];
</script>
Edit: You need to do some trickery: How to show <div> tag literally in <code>/<pre> tag? Which says that you need to escape your < and > characters in your tag to < and > for them to show in the <pre>. The example below has been modified to show this.
You should try using the html <pre> tag, it's commonly supported and does exactly what you're asking for:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
<pre>
<script type="text/javascript">
console.log('hi');
</script>
</pre>
should show something like
<script type="text/javascript">
console.log('hi');
</script>

Replace a script with another using Js and checkbox?

I'm creating a page which is suppose to be a little interactive. The user is suppose to be able to change a bunch of information by checking off an checkbox.
Index.php:
<span id="changeIt">Deactivated! - [ChangeMod]<img src="pic/deactivated.png"></span>
<form action="">
<input type="checkbox" id="checkboxChange" onclick="ChangeEverything();">Change Everything!</input>
</form>
<script TYPE="text/javascript" SRC="script/map_checkbox.js"></script>
map_checkbox.js:
var checkbox6 = document.getElementById("checkboxChange");
var posting6 = document.getElementById("changeIt");
var script = document.createElement("scriptChange");
function ChangeEverything(){
if (checkbox6.checked){
posting6.innerHTML="Activated! - [ChangeMod]<img src='pic/activated.png'>" ;
script.src = 'scriptMain.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(scriptChange);
}
else{
posting6.innerHTML="Deactivated! - [ChangeMod]<img src='pic/deactivated.png'>" ;
script.src = 'scriptSec.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(scriptChange);
}
}
Is it possible to overwrite the script like this, or do I have to use another method?
i think you have a problem with the
var script = document.createElement("scriptChange");
tou have to put the tag NAME
var script = document.createElement("script");

How to add script code using javascript?

I want to add script tag using javascript, but I am not able to get it work. Below is code. I want to add this code in bigcommerce cart page.
var duration = document.getElementsByName("cartdata");
var cartstr = '<!-- MyBuys Page Parameters ā€“ Place in <body> element -->';
cartstr += '<script type="text/javascript">';
cartstr += 'mybuys.setPageType("SHOPPING_CART");';
cartstr += 'mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->';
cartstr += 'mybuys.set("amount","99.34");';
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
cartstr += 'mybuys.addCartItemQtySubtotal("'+n[0]+'","'+n[1]+'","'+n[2]+'");'+'<br>';
}
cartstr += '</script>';
cartstr += '<!-- End MyBuys Page Parameters -->';
//alert(cartstr);
var script = document.createElement("script");
script.type = "text/javascript";
script.text = cartstr; // use this for inline script
document.body.appendChild(script);
I want below code added to page:
<!-- MyBuys Page Parameters ā€“ Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
This demonstrates how to dynamically add JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var optionalFunctionLoaded = false;
var commonFunction = function() {
console.log("test button clicked " + (new Date()).toLocaleString());
if (!optionalFunctionLoaded) {
// get optionalSrc e.g. via AJAX, eventually providing actual input values
var optionalSrc = 'function optFun(){console.log("optional function");}';
// if optionalSrc is not empty
var script = document.createElement("script");
script.innerHTML = optionalSrc;
document.head.appendChild(script);
optionalFunctionLoaded = true;
}
if(optionalFunctionLoaded) optFun();
}
</script>
</head>
<body>
<button id ="testButton">test</button>
<script type="text/javascript">
document.getElementById("testButton").onclick = commonFunction;
</script>
</body>
</html>
Tested with Firefox 24.0 / Linux.
The solution is to just add the code to the page:
<!-- MyBuys Page Parameters ā€“ Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
Why use JavaScript to put it there? Just add it to the page. You might have to adjust it a bit with your loop:
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
You should just be executing the code, there is no need to build the string. In the end, what you are trying to do is the same thing as running the code! Just execute it.
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com");
mybuys.set("amount","99.34");
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
I don't know why would you want to do that. But if you really want to, here is a way you could try.
$('body').append("console.log('blah');")
OR
$('body').html($('body').html()+"console.log('blah');")
Replace console.log('blah') with your code
Note this is assuming you are using JQuery.
If not, you can still use Native Javascript to do something similar. Just search for creating an element and adding it to another using vanila javascript and you'll get lots of information on google.
Although, as epascarello says, its not a good idea to do this. Its basically a code smell and you can improve your code.
Hope this helps.

use tags <script> with if and else

I have some script tag like this:
<script src="cordova-2.5.0.js"></script>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.mobile-1.1.1.min.js"></script>
<script src="js/jquery.xdomainajax.js"></script>
<script src="js/xml2json.js"></script>
<script src="js/ZipPlugin.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.ui.touch-punch.min.js"></script>
<script src="js/prefixfree.min.js"></script>
This is my app i wrote using phonegap for android but i want to use code in web. And i dont use all for web page.
Have any way to do it like using if else like this in html:
if(anything) {
<script src="cordova-2.5.0.js"></script>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.mobile-1.1.1.min.js"></script>
<script src="js/jquery.xdomainajax.js"></script>
<script src="js/xml2json.js"></script>
<script src="js/prefixfree.min.js"></script>
} else {
<script src="js/ZipPlugin.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.ui.touch-punch.min.js"></script>
}
I am a dumper, please help me.
Thanks for reading!!!
Edit:
if i want to change my script tag:
<script src="js/prefixfree.min.js"></script>
Become like this:
<script src="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/js/prefixfree.min.js"></script>
Have anyway to make a variable like:
var key ="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/"
And then use in tag like this:
<script src = "key + 'js/prefixfree.min.js'"></script>
How about this,
function registerScript(scriptPath) {
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = scriptPath;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(scriptTag, s);
}
if (anything) {
registerScript("cordova-2.5.0.js");
}
For the first part. you can do this:
if (anything) {
$('head').append('<script src="cordova-2.5.0.js"></script>')
.append('<script src="js/jquery-1.7.2.min.js"></script>')
.append('<script src="js/jquery.mobile-1.1.1.min.js"></script>')
.append('<script src="js/jquery.xdomainajax.js"></script>')
.append('<script src="js/xml2json.js"></script>')
.append('<script src="js/prefixfree.min.js"></script>')
} else {
$('head').append('<script src="js/ZipPlugin.js"></script>')
.append('<script src="js/jquery-ui.min.js"></script>')
.append('<script src="js/jquery.ui.touch-punch.min.js"></script>')
}
To change the script tag, do this:
var key ="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/"
$('script[src="js/prefixfree.min.js"]').attr('src', key + 'js/prefixfree.min.js');
Using jquery template :
DEMO : http://jsfiddle.net/abdennour/R36Qc/3/
Your template :
<script id="myscripts" type="text/x-jquery-tmpl">
<script src="${myurl}" type="text/javascript">
{{html "</sc"+"ript>"}}
</script>
Your javascript code :
$('#myscripts').tmpl(myarray).prependTo('head')
The branching (if) is done on array of String (src of js) :
var myarray=[]
if (anything) {
myarray=[{myurl:"cordova-2.5.0.js"},
{myurl:"js/jquery-1.7.2.min.js"},
{myurl:"js/jquery.mobile-1.1.1.min.js"},
{myurl:"js/jquery.xdomainajax.js"},
{myurl:"js/xml2json.js"},
{myurl:"js/prefixfree.min.js"},
{myurl:"js/jquery.mobile-1.1.1.min.js"}
]
} else {
myarray=[{myurl:"js/ZipPlugin.js"},
{myurl:"js/jquery-ui.min.js"},
{myurl:"js/jquery.ui.touch-punch.min.js"} ]
}
See : https://stackoverflow.com/a/5462679/747579
To check result , open browser inspector :
You could make a script to create all the scripts node like:
<script>
var head= document.getElementsByTagName('head')[0];
var key = '';
if(anything) key = 'http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/';
var scripts = new Array()
scripts[0] = 'js/prefixfree.min.js';
scripts[1] = 'js/foo.js';
for(var s in scripts) {
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= key + s;
head.appendChild(script);
}
</script>
You could use pure javascript like that:
<script>
var key ="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/",
file=document.createElement('script');
file.type = "text/javascript";
file.src = key + 'js/prefixfree.min.js';
document.getElementsByTagName("head")[0].appendChild(file);
</script>
<script>
if(foo) {
document.write('<script src="a.js"><\/script>');
} else {
document.write('<script src="b.js"><\/script>');
}
</script>
In this case document.write is a valid option. The script tags are blocking anyway.
You can include script files dynamically using JavaScript. See an example here:
Load jQuery with Javascript and use jQuery

Categories

Resources