1

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>
4
  • can you elaborate on "always get errors"? what errors? Commented Jul 26, 2012 at 13:15
  • What is the error? Sounds like you are trying to do something that is not allowed for security reasons. I believe you are prohibited from manipulating scripts on iframes for XSS concerns. Commented Jul 26, 2012 at 13:16
  • What is the point of putting javascript code inside the iframe rather than executing it directly? Commented Jul 26, 2012 at 13:16
  • the error about </script> .. you can test at xaluan.com/t.php .the point of puting javascript in iframe cause it from adnetwork.. i using their code in the mobile web site version .. the JavaScript ( not async type ) block other element of the page until it loaded, i'm trying to get rid of it by load ads same time with content.. Commented Jul 26, 2012 at 13:46

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.