I read the similar threads (Open page in new window without popup blocking - too old and non-React-based, In ReactJS opening pdf in a new tab triggers browser's popup warning - didn't work) but they didn't help:
In React/NextJS I'm presenting a new browser tab with a PDF byte[] response generated on the server. Everything works and my response
contains the byte array (verified).
const handlePrint = async (data: DataBean) => {
// Create payload for POST from passed-in data object
const payload = { ... };
// This works
const response = await post<any, typeof payload>("/create-pdf", payload);
// Now present in a new browser tab
const blob = new Blob([response], {type: "application/pdf;charset=utf-8"});
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
The onClick source is
<a href="javascript:void(0)" onClick={(e) => handlePrint(data)} title="Print PDF">Print PDF</a>}
There is a popup suppressed by the browser's popup blocker. I followed the 2-param window.open(url, '_blank')
approach. There's also a blob
with a URL.createObjectURL(blob)
used to obtain the byte array result.
I read the similar threads (Open page in new window without popup blocking - too old and non-React-based, In ReactJS opening pdf in a new tab triggers browser's popup warning - didn't work) but they didn't help:
In React/NextJS I'm presenting a new browser tab with a PDF byte[] response generated on the server. Everything works and my response
contains the byte array (verified).
const handlePrint = async (data: DataBean) => {
// Create payload for POST from passed-in data object
const payload = { ... };
// This works
const response = await post<any, typeof payload>("/create-pdf", payload);
// Now present in a new browser tab
const blob = new Blob([response], {type: "application/pdf;charset=utf-8"});
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
The onClick source is
<a href="javascript:void(0)" onClick={(e) => handlePrint(data)} title="Print PDF">Print PDF</a>}
There is a popup suppressed by the browser's popup blocker. I followed the 2-param window.open(url, '_blank')
approach. There's also a blob
with a URL.createObjectURL(blob)
used to obtain the byte array result.
1 Answer
Reset to default 0I figured it out. To avoid popup blockers, window.open
has to be called BEFORE the actual response is written. Thus, this is working:
// Immediately open a new tab to prevent popup blocking
let newTab = window.open();
// Get response
const response = await post<any, typeof payload>("/create-pdf", payload);
//... Other...: decoding from Base64, etc.
const blob = new Blob([bytes], {type: 'application/pdf'});
const url = URL.createObjectURL(blob);
if (newTab) {
newTab.location.href = url;
}