Reputation: 4793
I am currently receiving parts of a webpage through an XHR, and then parsing them using the DOMParser. After this I change some of the elements, but I am failing to append the document to the iFrame.
The document that is parsed is all right, but when appending this document to the iFrame by calling iFrame.contentDocument = parsedDocument
, iFrame.contentDocument
stays empty (actually there are html, head and body tags but their content is empty).
I am parsing the received data like so:
var parser = new DOMParser();
var parsedDocument= parser.parseFromString(xhr.response, 'text/html');
And my expectation was to do something like this:
iFrame.contentDocument = parsedDocument;
Upvotes: 4
Views: 1742
Reputation: 19112
Like epascarello said in the comments, the following will work:
var doc = document.getElementById('iframeId').contentWindow.document;
doc.open();
doc.write(xhr.response);
doc.close();
But, since you need to modify the document before placing it inside the iframe, you'll first need to do this:
//your code
var parser = new DOMParser();
var parsedDocument = parser.parseFromString(xhr.response, 'text/html');
//put your required edits here
parsedDocument.getElementById('foo').style.color = 'red'; //example
//now to get back the edited HTML code as a string
var newHTML = parsedDocument.documentElement.outerHTML;
//and now for the code epascarello mostly wrote
var doc = document.getElementById('iframeId').contentWindow.document;
doc.open();
doc.write(newHTML);
doc.close();
You might also want to specify a doctype there, by replacing the line of doc.write(newHTML);
with:
doc.write('<!DOCTYPE html>'+ newHTML);
since the document.documentElement.outerHTML
won't contain the doctype with it.
Upvotes: 2