MatthewHerbst / react-to-print

Print React components in the browser. Supports Chrome, Safari, Firefox and EDGE
MIT License
2.06k stars 221 forks source link

onAfterPrint is called before print iframe appears #689

Closed DmytroLynda closed 5 months ago

DmytroLynda commented 7 months ago

Hi.

I've noticed, that the onAfterPrint may be called before printing iframe is opened. Here is my code:

const { data: order, error } = useOrderPrint(`${orderNumber}`);
const printElementRef = useRef<HTMLDivElement>(null);
const print = useReactToPrint({
    content: () => printElementRef.current,
    onAfterPrint: () => {
      window.close();
    },
});

useEffect(() => {
    if (order) {
      print();
    }
}, [order, print]);

return (
<div className="flex max-w-screen-md flex-col gap-8 text-grey-0100 print:m-6"
        ref={printElementRef}>
// nested components...
</div>
);

It seems to happen randomly when I open the page. So sometimes the print iframe is opened correctly, and sometimes it renders the component and calls window.close() before iframe is rendered.

I also get the following message in the console:

Scripts may close only the windows that were opened by them.
onAfterPrint @ 5873-2fcfb030c2360765.js:1
(anonymous) @ 7116-16a55807edf1f37c.js:1
setTimeout (async)
t.startPrint @ 7116-16a55807edf1f37c.js:1
t.triggerPrint @ 7116-16a55807edf1f37c.js:1
_ @ 7116-16a55807edf1f37c.js:1
u.onload @ 7116-16a55807edf1f37c.js:1
load (async)
(anonymous) @ 7116-16a55807edf1f37c.js:1
d.onload @ 7116-16a55807edf1f37c.js:1
load (async)
t.handlePrint @ 7116-16a55807edf1f37c.js:1
t.handleClick @ 7116-16a55807edf1f37c.js:1
(anonymous) @ 7116-16a55807edf1f37c.js:1
(anonymous) @ 7116-16a55807edf1f37c.js:1
(anonymous) @ 5873-2fcfb030c2360765.js:1
uU @ framework-2645a99191cfc5e9.js:9
oV @ framework-2645a99191cfc5e9.js:9
o @ framework-2645a99191cfc5e9.js:9
x @ framework-2645a99191cfc5e9.js:33
T @ framework-2645a99191cfc5e9.js:33

There is also the following error, but I get it even when the iframe is rendered successfully

['Printing failed because the `contentWindow` of the… https://github.com/gregnb/react-to-print/issues/'] 
0 : 
"Printing failed because the `contentWindow` of the print iframe did not load. This is possibly an error with `react-to-print`. Please file an issue: https://github.com/gregnb/react-to-print/issues/"
length :  1

Here is react-to-print version: "react-to-print": "^2.15.1",

Do you have any suggestions?

MatthewHerbst commented 6 months ago

Hello. Apologies for the delayed response.

First, regarding the window.close, what window are you trying to close? The error seems reasonable: the browser is trying to prevent your script from closing the current window, which was presumably opened by the user when they went to your page, not be the script.

Second, regarding the early firing of onAfterPrint, which browser are you using? This is a known issue for example in Safari.