Reputation: 63
I have been using the JavaScript print() method for printing the content of a page. The code hasn't been changed in 2 years and it was working on Firefox until a few days ago, when I got the Version 100.0.
This is the code I have been using to print:
print() {
const printableElement = Printer.createPrintableElement()
const printableContentWindow = printableElement.contentWindow
if (!printableContentWindow) {
return
}
const { styles, html } = this.proceedContent()
printableContentWindow.document.head.innerHTML = `${styles}`
printableContentWindow.document.body.innerHTML = html
printableContentWindow.focus()
printableContentWindow.print()
}
static createPrintableElement() {
const printableElement = document.createElement('iframe')
printableElement.width = '0'
printableElement.height = '0'
document.body.appendChild(printableElement)
return printableElement
}
static collectPageStyles() {
return [...document.querySelectorAll('link[rel="stylesheet"], style')].reduce(
(acc, style) => (acc += style.outerHTML),
''
)
}
filterContentElements() {
const { ignoreElements } = this.options
const content = this.element
if (ignoreElements.length === 0) {
return content
}
ignoreElements.forEach((selector) => {
const elementsToDelete = content.querySelectorAll(selector)
elementsToDelete.forEach((node) => node.remove())
})
return content
}
proceedContent() {
const styles = Printer.collectPageStyles()
const html = this.filterContentElements().innerHTML
return { styles, html }
}
I try to debug it and I realized it fails on the method print()
, specifically on printableContentWindow.print()
. The error it shows on browser console is this:
And when it occurs, the page to be printed is completely blank.
This code works perfectly on Chrome, Opera and Opera GX.
Any idea what could be happening?
Upvotes: 1
Views: 689
Reputation: 83
I think it may work if you change your print function to the following:
print() {
const printableElement = Printer.createPrintableElement()
const printableContentWindow = printableElement.contentWindow
if (!printableContentWindow) {
return
}
setTimeout(function ()
{
const { styles, html } = Printer.proceedContent()
}, 100);
printableContentWindow.document.head.innerHTML = `${styles}`
printableContentWindow.document.body.innerHTML = html
setTimeout(function ()
{
printableContentWindow.focus()
printableContentWindow.print()
}, 100);
}
This is a 'racing' bug in FireFox. I was having similar issues and found this answer, Firefox won't print unless I set a breakpoint?, which pointed me in the right direction.
Upvotes: 1