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 f
Salaam
blob:http://***.***.***.**/392d72e4-4481-4843-b0d4-a753421c0433
Blobs are not blocked by chrome but are blocked by AdBlock extension Either:
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);
}
In plain vanilly javascript (because I don't have jquery)
let newWindow = window.open('/file.html');
newWindow.onload = () => {
var blobHtmlElement;
blobHtmlElement = document.createElement('object');
blobHtmlElement.style.position = 'fixed';
blobHtmlElement.style.top = '0';
blobHtmlElement.style.left = '0';
blobHtmlElement.style.bottom = '0';
blobHtmlElement.style.right = '0';
blobHtmlElement.style.width = '100%';
blobHtmlElement.style.height = '100%';
blobHtmlElement.setAttribute('type', 'application/pdf');
blobHtmlElement.setAttribute('data', fileObjectURL);
newWindow.document.title = 'my custom document title';
newWindow.document.body.appendChild(blobHtmlElement);
};
/file.html
is an almost empty html file, source:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</body>
</html>
Tested in chrome & firefox (on 20/november/2019)
I do not have Ad blocker. Looks like setting the blob type explicitly to application/pdf will solve this issue.
const newBlob = new Blob([blobData], {type: "application/pdf"});
Work around way to by pass adblocker.
coffeescript & jquery
$object = $("<object>")
$object.css
position: 'fixed'
top: 0
left: 0
bottom: 0
right: 0
width: '100%'
height: '100%'
$object.attr 'type', 'application/pdf'
$object.attr 'data', fileObjectURL
new_window = window.open()
new_window.onload = ->
$(new_window.document.body).append $object
The cause is probably adblock extension (I had exactly the same problem).