how add and execute script and html to iframe - javascript

i am trying to add a script and some html to iframe or a div the html & script tag is added but it does not execute
html
<script>
var gw_d = "ad1";
var gw_w = "300";
var gw_h = "250";
var gw_ad = "ad1";
</script>
<script type="text/javascript" src="js.js"></script>
<div id="ad1">
</div>
js.js
$("#" + gw_d).width(gw_w).height(gw_h);
$.get("/bw/" + gw_ad + ".txt", function(data) {
$('<iframe>', {
id: 'myFrame',
frameborder: 0,
scrolling: 'no',
width:gw_w,
height:gw_h,
}).appendTo("#" + gw_d).contents().find('body').append(data);
});
ad1.txt
<p align="center">
<script src="http://tag.contextweb.com/TagPublish/getjs.aspx?action=VIEWAD&cwrun=200&cwadformat=300X250&cwpid=504351&cwwidth=300&cwheight=250&cwpnet=1&cwtagid=18972"></script>
</p>
Fiddle

Scripts like that appears to break when </script> is included in the string. A workaround to that could be to add the elements through dom manipulation:
iframe = $('<iframe>');
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://tag.contextweb.com/TagPublish/getjs.aspx?action=VIEWAD&cwrun=200&cwadformat=300X250&cwpid=504351&cwwidth=300&cwheight=250&cwpnet=1&cwtagid=18972";
// Or:
script.text = "Your code here!"
iframe[0].appendChild(script);
Working Fiddle

Related

How to insert special script into header?

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

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.

document.write alternativ without overwriting the DOM / side

got a problem with the usage of
document.write()
i want to overwrite a div in which a adbanner is loaded and i cant find any solution to this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
var i = 0;
var newImage;
function refresh() {
i++;
if (i >= 5) {
writeAd();
i = 0;
}
}
function writeAd() {
var arr = box1.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML)
}
</script>
</head>
<body
<h1>Bilder Random</h1>
<input type="button" onclick="refresh()" value="go!" />
<div id="box1" class="superbanner">
<table cellspacing="0" cellpadding="0" border="0" class="ad1">
<script language="JavaScript">
if (typeof (WLRCMD) == "undefined") {
var WLRCMD = "";
}
if (typeof (adlink_randomnumber) == "undefined") {
var adlink_randomnumber = Math
.floor(Math.random() * 1000000)
}
document
.write('<scr'
+ 'ipt language="JavaScript" src="http://ad.de.doubleclick.net/adj/oms.skol.de/localnews_bilder;oms=localnews_bilder;reg=;nielsen=3b;dcopt=ist'
+ WLRCMD + ';sz=728x90;tile=1;ord='
+ adlink_randomnumber + '?"><\/scr'+'ipt>');
</script>
</table>
</div>
</body>
</html>
My main problem is the document.write() in the adbanner script part.
i can reload the page with 5 clicks on the button but it overwrites the whole DOM
is there any possability to use something else than document.write()
to insert the adbanner at the beginning of the page load and when calling
the function writeAd()?
This is how you should load JS files dynamically:
if (window.isReady) { //after page was loaded, we must manually add new SCRIPT tag into HEAD
var script = document.createElement('script'), head = document.head || document.getElementsByTagName('head')[0];
script.type = 'text/javascript';
script.src = fileName;
head.appendChild(script);
}
else { //otherwise we are still in a progress of creating HEAD or BODY and we can simply write into document
var write = 'write'; //prevents JSlint from saying that document.write is evil ;)
document[write]('<script type="text/javascript" src="' + fileName + '"></script>');
}
To detect if window is loaded:
window.onload = function() { window.isReady = true; }

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

adding html into a div without id

i'm trying to add some html code with javascript and jQuery into a div without an id, but with a class
i'm trying to have it done like this, but without success...
flie.js :
$(".myClassName").ready(function(){
$(this).innerHTML = "<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>";
});
i'm loading the .js file with this html code
.html file :
<div class="myClassName">
</div>
<script>
(function()
{
if (window['ImportFlag'] == undefined || window['ImportFlag'] == void 0) {
var myScript = document.createElement('script');
myScript.type = 'text/javascript';
myScript.src = 'file.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(myScript, s);}
window['ImportFlag'] = 1;
})();
</script>
$(document).ready(function(){
$(".myClassName").html("<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>");
});
You may try like this
<div class="myClassName">
</div>
<script type="text/javascript" src="file.js">
</script>ā€‹
file.js
$(document).ready(function(){
$('.myClassName').html("<img src=\"http://mywebsite.com/img.png\" /> <span>some text</span>");
});ā€‹
You should firs ensure that jQuery is loaded BEFORE loading file.js. Then you should use jQuery's functions to set the div inner HTML.
This is a minimalist example :
<html>
<head></head>
<body>
<div class="myClassName">
</div>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script>
(function()
{
if (window['ImportFlag'] == undefined || window['ImportFlag'] == void 0) {
var myScript = document.createElement('script');
myScript.type = 'text/javascript';
myScript.src = 'file.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(myScript, s);}
window['ImportFlag'] = 1;
})();
</script>
</body>
</html>
Then, file.js :
$(document).ready(function(){
$(".myClassName").html("... <span>some text</span>");
});
The jQuery ready() function should be called on the document object, not on an element. It evokes a DOM-ready handler, and can be called using the following syntax (from the official documentation):
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
Matei Mihai and muthu's answers here show you how this works for your example.

Categories

Resources