I have a maybe strange question but still a little bit annoying .
In our interface we have created an user interaction by simply clicking a button and previewing an PDF file on a new tab . Everything is working fine , but if you have you Chrome AdBlocker extension activated it automatically triggers and it doesn't allow to the user to preview his document . It is a little bit annoying , because i had to display a big message for each user in order to have a properly working app to disable their AdBlocker extensions . So i ask myself is there a way to prevent this scenario?
const postHeader = {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
'Accept': 'application/pdf',
'Authorization': 'Bearer ' + token
}
};
// Prepare request to the BE body
const postBody = {
customerNumber,
tenant
};
if (!isNaN(pdfID)) {
// Firing the request to the BE
axios.post(serverUrl + '/api/user/bill/' + pdfID, postBody, postHeader)
.then((response) => {
// If there is blob data with the PDF, we show it
if (response.data.byteLength > 0) {
// We create a file from the blob
const file = new Blob([response.data], {
type: 'application/pdf'
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, "output.pdf");
} else {
const objectUrl = URL.createObjectURL(file);
window.open(objectUrl);
console.log(objectUrl)
}
A common pop-up blocking strategy in browsers is to require any new window/tab to be opened as a direct result of a user interaction. Since your click event handler initiates an asynchronous process and you don't open the new window until it has resolved, this means that the browser will block it because too much time has elapsed between the user interaction and window.open()
.
The easiest way to fix this is simply to open the window before you start reading the data and then write to it once you have the data ready. Something like this should work:
if (!isNaN(pdfID)) {
const pdfWindow = window.open('about:blank');
// Firing the request to the BE
axios.post(serverUrl + '/api/user/bill/' + pdfID, postBody, postHeader)
.then((response) => {
// If there is blob data with the PDF, we show it
if (response.data.byteLength > 0) {
// We create a file from the blob
const file = new Blob([response.data], {
type: 'application/pdf'
});
const objectUrl = URL.createObjectURL(file);
pdfWindow.document.location.href = objectUrl;
You can also use a static page as placeholder instead of about:blank
, e.g. a page that just displays a message, like Loading...
.
I'm not sure how to handle that window.navigator.msSaveOrOpenBlob
thing as I'm not at all familiar with it.