Reputation: 1313
I trying to create iframe then add script to it and script will run. Iframe created, but it always get errors in process of appending script to that iframe. Please help.
<div align="center" id="adframe1">
<script type="text/javascript">
var response1 = '<script>var ad_unit="123";</scr'+'ipt><script src="http://abc.com/abc.js"></scr'+'ipt>';
$('<iframe id="adframe1mopub"/>').appendTo('#adframe1');
$('#adframe1mopub').ready(function() {
$('#adframe1mopub').contents().find('body').append(response1);
});
</script>
</div>
Upvotes: 1
Views: 4387
Reputation: 14967
You can try this script:
HTML:
<div id=container-iframe></div>
JS:
var response1 = '<script>var ad_unit="123";</scr' + 'ipt><script src="http://abc.com/abc.js"></scr' + 'ipt>';
$('<iframe></iframe>', { id: 'adframe1mopub' }).bind('load', function(event) {
if (!this.contentWindow) {
return;
}
this.contentWindow.document.body.innerHTML += response1;
}).appendTo('#container-iframe');
But it would be best way to implement this:
$('<iframe></iframe>', { id: 'myiframe' }).bind('load', function(event) {
if (!this.contentWindow) {
return;
}
var scripWidthCode = document.createElement('script');
scripWidthCode.type ='text/javascript';
scripWidthCode.innerText = 'var ad_unit="123";';
this.contentWindow.document.getElementsByTagName('head')[0].appendChild(scripWidthCode);
var scripWidthSrc = document.createElement('script');
scripWidthSrc.type ='text/javascript';
scripWidthSrc.src = 'http://abc.com/abc.js';
this.contentWindow.document.getElementsByTagName('head')[0].appendChild(scripWidthSrc);
}).appendTo('#container-iframe');
test
Upvotes: 3