I have a Lightning component which has an iframe to a visualforce page:
<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId">
<iframe aura:id="myFrame" id="myFrame" src="/visualforcepage"></iframe>
<lightning:button label="Print" onclick="{! c.handleClick }" />
</aura:component>
Or LWC
<template>
<iframe width="100%" height="600" src={frameUrl}></iframe>
<button onclick={handlePrint} class="slds-button slds-button_brand">Print</button>
</template>
Using JS:
handlePrint() {
const iframe = this.template.querySelector('iframe');
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
I would like to press a button in the Lightning component to print the contents of the iframe.
I have tried:
window.frames['myFrame'].focus();
window.frames['myFrame'].print();
And
document.getElementById("myFrame").contentWindow.print();
And
var myFrame = cmp.find('myFrame').getElement();
myFrame.focus();
myFrame.print();
And
var myFrame = cmp.find('myFrame').getElement();
myFrame.contentWindow.focus();
myFrame.contentWindow.print();
But none of the approaches make the print dialog appear.
Question
- How can I fire the
print()
method on an iframe from within a Lightning component?
print()
method on the top-level component