react-new-window
react-new-window copied to clipboard
How can I print whether the new window is under focus or has lost its focus in the main/parent window.
You can use a reference to set focus to the popup window like this (TypeScript):
const newWindowRef = useRef<NewWindow | null>(null);
useEffect(() => {
if (newWindowRef && newWindowRef.current) {
const currentWindow = newWindowRef.current as NewWindow;
// @ts-ignore TS thinks that the window property is private (nope) so it throws false positive errors.
const popupWindow = currentWindow.window as typeof window;
/**
* Handle the afterprint event
* @param {Event} e Afterprint event
*/
const handleAfterPrint = (e: Event) => {
e.preventDefault();
// Uncomment the line below to close the popup window when we are done printing.
// popupWindow.close();
}
// This will bring up the print dialog as soon as the popup window has mounted.
popupWindow.addEventListener('afterprint', handleAfterPrint);
popupWindow.focus();
popupWindow.print();
// Clean up after ourselves.
return () => popupWindow.removeEventListener('afterprint', handleAfterPrint);
}
}, [newWindowRef]);
return (
<>
<NewWindow
title="Print Demo"
ref={newWindowRef}
>
<h1>
Whatever you want to print goes here.
</h1>
</NewWindow>
</>
)
Also, you can play with the onOpen prop that pass the window instance.