0

I have an htmlString. And I am putting that string into an iframe. The code is

var iframe = document.createElement('iframe'); 
var html = '<html> <head></head> <body> //contents </body> </html>';

document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

Now what I want to do is insert a tag

<base href="some url" >

into the head of the htmlString. And then I want to append the iframe into the dom and write the htmlString into that iframe.

How to maniuplate the htmlString before inserting it into iframe?

Aniket
  • 4,926
  • 12
  • 41
  • 54

4 Answers4

1

Here you go: https://jsfiddle.net/tjcwyem6/

I used the following JavaScript:

var iframe = document.createElement('iframe'),
    html = '<html> <head></head> <body> //contents </body> </html>',
    newurl = "https://www.facebook.com/",
    basehref = "<base href='" + newurl + "'>",
    n = html.indexOf("</head>");

var newhtml = [html.slice(0, n), basehref, html.slice(n)].join('');

document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(newhtml);
iframe.contentWindow.document.close();

console.log(newhtml);

My modifications do the following:

  1. Store your url value in newurl.
  2. Put that in a string basehref.
  3. Get the place in your HTML string where </head> is.
  4. Add basehref to newhtml by slicing and joining the strings.
fnune
  • 5,256
  • 1
  • 21
  • 35
0

You can be able to append iframe content using jquery like -

$("iframe").contents().find("head").append('<base href="some url" >');
Pragnesh Khalas
  • 2,908
  • 2
  • 13
  • 26
  • Although this is cleaner and more natural, it doesn't manipulate the string before inserting it into the iframe. – fnune May 18 '16 at 09:13
0

You can manipulate the html by loading it into jquery as XML and using jquery to manipulate:

var xml = $.parseXML("<html> <head></head> <body> //contents </body> </html>");    
$("head", xml).append("<base url='x'/>")

var html;
if (window.ActiveXObject) {
    html = xml.xml;
} else {
    html = (new XMLSerializer()).serializeToString(xml);
}

iframe.contentWindow.document.write(html);

This answer for xml to html details

You can't load the html as html into jquery as it strips body/head.

Community
  • 1
  • 1
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
0
String.prototype.insertAt=function(index, string) { 
        return this.substr(0, index) + string + this.substr(index);
}
var myhtml = "<html> <head></head> <body></body> </html>";
var m = myhtml.indexOf("</head>");
myhtml = myhtml.insertAt(m, '<base href="some url" >');
console.log(myhtml);
Astaroth
  • 11
  • 2