I have an iframe element inside my component and I need to somehow detect when the URL of that iframe changes. What I have tried so far:
onLoad callback, but this does not trigger every time I redirect in the iframeReact.useCallback but also does not work as I wanted totimeout and get the URL from the iframe every x secondsMinimalistic code example below
export const XComponent = (props: XComponentProps) => {
const ref = React.useRef<any>();
1.
const onLoad = () => {
const url = ref.current.contentWindow.location.href;
// do stg with url
}
2.
const getRef = React.useCallback((node: any) => {
// store node into state, this was not triggered properly either
}, []);
3.
React.useEffect(() => {
const interval = setInterval(() => {
const url = ref.current.contentWindow.location.href;
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div className={ styles.albertStoremanTab }>
<div className={ styles.container }>
<iframe id={"iframe-my-id"} onLoad={onLoad} src={props.defaultUrl} ref={ref}></iframe>
</div>
</div>
);
};
That's simple:
useEffect(() => {
// It runs only when defaultUrl changes
}, [props.defaultUrl])
Did you try using ref.current in the dependency array of the useEffect?
useEffect(() => { setURL(ref.current.contentWindow.location.href) }, [ref.current])