1

I would like to load an iframe with dynamic html and script, and then execute it. In my html document I have this simple iframe tag:

<iframe></iframe>

And my jQuery script, which loads on Document Ready, and is supposed to prepare the iframe:

$( document ).ready(function() {
  // Add jQuery lib  
  $('iframe').contents().find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>)');

  // Add div to body
  $('iframe').contents().find('body').html('<div id="myDiv">Initial</div>');

  // Add script to change div
  $('iframe').contents().find('body').html('<script>$("#myDiv").html("Changed")</script>');
});

The above jQuery script should do the following inside the iframe:

  1. Load the jQuery library
  2. Setup a div in body with a simple text in it
  3. Setup a jQuery script in body, where I use a jQuery selector to change the content of the div

But I don't get very far, as the console window says:

Uncaught SyntaxError: Unexpected token ILLEGAL

What I want with this question is to know how I can get the script inside the iframe to change its div's text to "Changed".

I have created a jsFiddle.

* UPDATE *

I don't see how this is a duplicate of Script tag in JavaScript string, which is about parsing strings in javascript. What my questions is about, is how I can load dynamic html and jQuery in an iframe and afterwards execute the script.

Community
  • 1
  • 1
mrturtle
  • 277
  • 3
  • 10

1 Answers1

3

You can use srcdoc, not all browser support this

do whatever you want in this attr

$( document ).ready(function() {
    console.log($('#myIframe'))
  // Add jQuery lib  
  $('#myIframe').attr('srcdoc', "<!DOCTYPE html>" +
"<html>" +
"<head>" +
  "<meta charset=\"utf-8\">" +
  "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">" +
  "<title><\/title>" +
  "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js\"><\/script>" +
  "<script>" +
    "$(function () {" +
      "$('body').html('<div id=\"myDiv\">Initial<\/div><button id=\"myButton\">Click to change<\/button>');" +

      "$('#myButton').on('click', function () {" +
        "$('#myDiv').html('Changed');" +
      "});" +
    "})" +
  "<\/script>" +
"<\/head>" +
"<body>" +
"<\/body>" +
"<\/html>")
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="myIframe"></iframe>
zhea55
  • 71
  • 3
  • Thanks. But as you write, it is not supported in all browsers. – mrturtle Oct 30 '15 at 10:16
  • Your solution actually seems to work in all major browsers, if I include this poly fill: https://github.com/jugglinmike/srcdoc-polyfill – mrturtle Oct 30 '15 at 13:33
  • Actually your code can running well. The error you see is the end html tag must change to <\/script>. The slash must be escape. – zhea55 Oct 30 '15 at 13:44