In react i need to be able to open a popup window https://developer.mozilla.org/en-US/docs/Web/API/Window/open and manage the events such as "mesage" https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage and "load" and "close" events.
However none of the events i have added listeners to are firing...
import * as React from 'react';
import './style.css';
import { useState, useRef } from 'react';
export default function App() {
const { login, error } = useOAuth();
return (
<div>
<button onClick={login}>Login</button>
</div>
);
}
const useOAuth = () => {
const [error, setError] = useState();
const popupRef = useRef<Window | null | undefined>();
const login = () => {
popupRef.current = openPopup('https://google.com');
popupRef.current.addEventListener('load', handlePopupLoad);
popupRef.current.addEventListener('close', handlePopupClose);
popupRef.current.addEventListener('message', handlePopupMessage);
};
const handlePopupLoad = (data) => {
console.log('load', data);
};
const handlePopupClose = (data) => {
console.log('close', data);
};
const handlePopupMessage = (data) => {
console.log('message', data);
};
const openPopup = (url: string) => {
const params = `scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,
width=500,height=600,left=100,top=100`;
return window.open(url, 'Login', params);
};
return {
login,
error,
};
};
https://stackblitz.com/edit/react-ts-qlfw9q?file=App.tsx
aside:
- Is there a way to differentiate between when a "user" closed the window using the "red x" button and when it was correctly closed using window.close().
- how can i nicely cleanup the popup once its closed.