fix: iframe srcDoc was not able to postMessage that can be received by onMessageReceived event. Match iframe by object not origin (#11809)

This commit is contained in:
Pallav Agarwal 2022-03-28 13:12:12 +05:30 committed by GitHub
parent 35b1546f78
commit b019fbae6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 10 deletions

View File

@ -75,16 +75,25 @@ function IframeComponent(props: IframeComponentProps) {
widgetId,
} = props;
const frameRef = useRef<HTMLIFrameElement>(null);
const isFirstRender = useRef(true);
const [message, setMessage] = useState("");
useEffect(() => {
const handler = (event: MessageEvent) => {
const iframeWindow =
frameRef.current?.contentWindow ||
frameRef.current?.contentDocument?.defaultView;
// Accept messages only from the current iframe
if (event.source !== iframeWindow) return;
onMessageReceived(event);
};
// add a listener
window.addEventListener("message", onMessageReceived, false);
window.addEventListener("message", handler, false);
// clean up
return () =>
window.removeEventListener("message", onMessageReceived, false);
return () => window.removeEventListener("message", handler, false);
}, []);
useEffect(() => {
@ -129,9 +138,9 @@ function IframeComponent(props: IframeComponentProps) {
{message ? (
message
) : srcDoc ? (
<iframe src={source} srcDoc={srcDoc} title={title} />
<iframe ref={frameRef} src={source} srcDoc={srcDoc} title={title} />
) : (
<iframe src={source} title={title} />
<iframe ref={frameRef} src={source} title={title} />
)}
</IframeContainer>
);

View File

@ -162,11 +162,6 @@ class IframeWidget extends BaseWidget<IframeWidgetProps, WidgetState> {
};
handleMessageReceive = (event: MessageEvent) => {
// Accept messages only from the current iframe
if (!this.props.source?.includes(event.origin)) {
return;
}
this.props.updateWidgetMetaProperty("message", event.data, {
triggerPropertyName: "onMessageReceived",
dynamicString: this.props.onMessageReceived,