I want to open a PDF in a new tab in chrome browser (Chrome 56.0.2924.87, Ubuntu 14.04) using window.open(fileObjectURL)
in javascript. I am creating the blob from base64 encoded data and do create an objectURL like this:
const fileObjectURL = URL.createObjectURL(fileBlob);
It works fine in latest Firefox browser. But in Chrome I can see that the new tab gets opened but then closed immediately. So I don't get any error in the console etc.
The only way it works in Chrome now is to give the base64 data directly to the window.open(fileBase64Data)
function. But I don't like the complete data being set in the url.
Maybe this is a safety issue with Chrome blocking opening of blobs?
The cause is probably adblock extension (I had exactly the same problem).
You must open new window before you put blob url in window:
let newWindow = window.open('/')
Also you can use some another page like /loading
, with loading indicator.
Then you need to wait newWindow loading, and you can push url of your blob file in this window:
newWindow.onload = () => {
newWindow.location = URL.createObjectURL(blob);
};
Adblock extension don't block it.
I'm using it with AJAX and ES generators like this:
let openPDF = openFile();
openPDF.next();
axios.get('/pdf', params).then(file => {
openPDF.next(file);
});
function* openFile() {
let newWindow = window.open('/pages/loading');
// get file after .next(file)
let file = yield;
// AJAX query can finish before window loaded,
// So we need to check document.readyState, else listen event
if (newWindow.document.readyState === 'complete') {
openFileHelper(newWindow, file);
} else {
newWindow.onload = () => {
openFileHelper(newWindow, file);
};
}
}
function openFileHelper(newWindow, file) {
let blob = new Blob([file._data], {type: `${file._data.type}`});
newWindow.location = URL.createObjectURL(blob);
}