Skip to content

Instantly share code, notes, and snippets.

@jeffskelton3
Last active October 7, 2020 20:06
Show Gist options
  • Save jeffskelton3/02aa4effb7297df866e90eca6c8a21fc to your computer and use it in GitHub Desktop.
Save jeffskelton3/02aa4effb7297df866e90eca6c8a21fc to your computer and use it in GitHub Desktop.
import React, { useRef } from 'react';
interface WidgetProps {
url: string;
onWidgetReady: (api: any) => void;
}
type UnsubscribeCallback = Function;
type Subscribe = <T = string>(
eventName: T,
handler: (payload: any) => void
) => UnsubscribeCallback;
type Publish = <T = string, U = object>(eventName: T, payload: U) => void;
type WidgetMessageEvent<T = string> = {
data: {
eventName: T;
payload: Record<string, any>;
};
} & MessageEvent;
const TARGET_ORIGIN = '*';
export const Widget = ({ url, onWidgetReady }: WidgetProps) => {
const frame = useRef<HTMLIFrameElement>(null);
const handleOnLoad = () => {
const publish: Publish = (eventName, payload): void => {
const iframe = frame.current;
iframe?.contentWindow?.postMessage(
{
eventName,
payload
},
TARGET_ORIGIN
);
};
const subscribe: Subscribe = (
eventName,
handler: <T>(payload: T) => void
): UnsubscribeCallback => {
const cb = (e: WidgetMessageEvent) => {
if (e.data.eventName !== eventName) return;
handler(e.data.payload);
};
window.addEventListener('message', cb);
return () => window.removeEventListener('message', cb);
};
onWidgetReady({
publish,
subscribe
});
};
return (
<div className="relative w-full h-full">
<iframe
title="record-explorer-widget"
ref={frame}
src={url}
onLoad={handleOnLoad}
frameBorder="0"
className={'absolute pin h-full w-full'}
scrolling="no"
data-testid="record-explorer-widget"
data-cy="record-explorer-widget"
/>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment