简体   繁体   中英

How to create iframe then append javascript to it with jQuery?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM