que1326
que1326

Reputation: 2325

How to append elements in head tag from iframe?

1 ) I want to dynamically create an iframe.

2 ) I have mocked data ( string templates ) for head and body tags.

3 ) I want to create the iframe with the given data from 2 )

Code

  var bodyHtml = '<p>Content</p>';
  var headHtml = '<title>Title</title>';

  var iframe = document.createElement('iframe');

  // inject the bodyHTML to locally iframe
  iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(bodyHtml );

  // headHtml how ?

  // inject my iframe in the DOM
  $('mySelector').append(iframe);

How do I inject the headHtml in the iframe head tag ?

Upvotes: 0

Views: 105

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075855

You've already done most of the work. The content of the document isn't just the body, it's the whole thing, so you build up the whole thing and then pass that to encodeURIComponent (rather than encodeURI):

var bodyHtml = '<p>Content</p>';
var headHtml = '<title>Title</title>';

var iframe = document.createElement('iframe');

// inject the bodyHTML to locally iframe
iframe.src = 'data:text/html;charset=utf-8,' + encodeURIComponent(
  "<!doctype html>" +
  "<html>" +
  "<head>" + headHtml + "</head>" +
  "<body>" + bodyHtml + "</body>" +
  "</html>"
);

// inject my iframe in the DOM
$('body').append(iframe);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or with ES2015+ syntax (in particular, a template literal):

// inject the bodyHTML to locally iframe
iframe.src = 'data:text/html;charset=utf-8,' + encodeURIComponent(`
  <!doctype html>
  <html>
  <head>${headHtml}</head>
  <body>${bodyHtml}</body>
  </html>
`);

Live Example:

const bodyHtml = '<p>Content</p>';
const headHtml = '<title>Title</title>';

const iframe = document.createElement('iframe');

// inject the bodyHTML to locally iframe
iframe.src = 'data:text/html;charset=utf-8,' + encodeURIComponent(`
  <!doctype html>
  <html>
  <head>${headHtml}</head>
  <body>${bodyHtml}</body>
  </html>
`);

// inject my iframe in the DOM
$('body').append(iframe);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Related Questions