kopia lustrzana https://gitlab.com/soapbox-pub/soapbox
SafeEmbed: autosize iframe height
rodzic
f1248018e6
commit
c79506e1fd
|
@ -1,4 +1,4 @@
|
||||||
import React, { useEffect, useRef } from 'react';
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
interface ISafeEmbed {
|
interface ISafeEmbed {
|
||||||
/** Styles for the outer frame element. */
|
/** Styles for the outer frame element. */
|
||||||
|
@ -19,6 +19,13 @@ const SafeEmbed: React.FC<ISafeEmbed> = ({
|
||||||
html,
|
html,
|
||||||
}) => {
|
}) => {
|
||||||
const iframe = useRef<HTMLIFrameElement>(null);
|
const iframe = useRef<HTMLIFrameElement>(null);
|
||||||
|
const [height, setHeight] = useState<number | undefined>(undefined);
|
||||||
|
|
||||||
|
const handleMessage = useCallback((e: MessageEvent) => {
|
||||||
|
if (e.data?.type === 'setHeight') {
|
||||||
|
setHeight(e.data?.height);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const iframeDocument = iframe.current?.contentWindow?.document;
|
const iframeDocument = iframe.current?.contentWindow?.document;
|
||||||
|
@ -29,11 +36,19 @@ const SafeEmbed: React.FC<ISafeEmbed> = ({
|
||||||
iframeDocument.close();
|
iframeDocument.close();
|
||||||
iframeDocument.body.style.margin = '0';
|
iframeDocument.body.style.margin = '0';
|
||||||
|
|
||||||
|
iframe.current?.contentWindow?.addEventListener('message', handleMessage);
|
||||||
|
|
||||||
const innerFrame = iframeDocument.querySelector('iframe');
|
const innerFrame = iframeDocument.querySelector('iframe');
|
||||||
if (innerFrame) {
|
if (innerFrame) {
|
||||||
innerFrame.width = '100%';
|
innerFrame.width = '100%';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (iframeDocument) {
|
||||||
|
iframe.current?.contentWindow?.removeEventListener('message', handleMessage);
|
||||||
|
}
|
||||||
|
};
|
||||||
}, [iframe.current, html]);
|
}, [iframe.current, html]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -41,6 +56,7 @@ const SafeEmbed: React.FC<ISafeEmbed> = ({
|
||||||
ref={iframe}
|
ref={iframe}
|
||||||
className={className}
|
className={className}
|
||||||
sandbox={sandbox}
|
sandbox={sandbox}
|
||||||
|
height={height}
|
||||||
title={title}
|
title={title}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
Ładowanie…
Reference in New Issue