react-new-window icon indicating copy to clipboard operation
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.

Open ampsteric opened this issue 5 years ago • 1 comments

ampsteric avatar Sep 07 '20 11:09 ampsteric

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>
        </>
    )

RyanNerd avatar May 14 '21 17:05 RyanNerd

Also, you can play with the onOpen prop that pass the window instance.

rmariuzzo avatar Nov 27 '22 05:11 rmariuzzo