Skip to content

Instantly share code, notes, and snippets.

@BetterProgramming
Created July 1, 2020 11:06
Show Gist options
  • Save BetterProgramming/cd161c1a720505a05d2e525a3c133b33 to your computer and use it in GitHub Desktop.
Save BetterProgramming/cd161c1a720505a05d2e525a3c133b33 to your computer and use it in GitHub Desktop.
import React from 'react';
const Iframe = (props) => {
let iframe_ref = null;
const writeHTML = (frame) => {
if (!frame) {
return;
}
iframe_ref = frame;
let doc = frame.contentDocument;
doc.open();
doc.write(props.content);
doc.close();
frame.style.width = '100%';
frame.style.height = `${frame.contentWindow.document.body.scrollHeight}px`;
};
return (
<iframe src="about:blank" scrolling="no" frameBorder="0" ref{writeHTML}
/>
);
};
export default Iframe;
@Andrii256
Copy link

and even better use not body.scrollHeight, but html.scrollHeight

@Andrii256
Copy link

i mean frame.contentDocument.documentElement.scrollHeight instead of frame.contentDocument.body.scrollHeight

@appukuttan-shailesh
Copy link

appukuttan-shailesh commented May 21, 2021

@Andrii256: could you post the updated script with the changes you proposed?

I agree: frame.contentDocument.documentElement.scrollHeight seems to be better.
I get error with frame.contentDocument.body.scrollHeight

@appukuttan-shailesh
Copy link

Also, how to handle changes in the height of the content? E.g. if there are items that collapse and expand to be displayed within the Iframe?
Simply loading it during onload doesn't suffice.

@Andrii256
Copy link

I dint try it so I'm not sure that it will help with Iframe, but it looks like there resizeObserver API. Possibly it can halp:) https://stackoverflow.com/questions/14866775/detect-document-height-change

@masoodalamhunzai
Copy link

nice work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment