Why does WebViewer instance is null?

I am integrating WebViewer using LWC on Salesforce platform. My PDF document is able to render without any problem. To do the page manipulation (text replacement), I need instance of the webViewer. Following is the code that I’m using. Can someone please what I’m doing wrong? I just spent 2 straight hours debugging this. But no luck.

const viewerElement = this.template.querySelector('div')
const viewer = new PDFTron.WebViewer({
    path: libUrl, // path to the PDFTron 'lib' folder on your server
    custom: JSON.stringify(myObj),
    // initialDoc: url,
    config: configUrl,
    fullAPI: true,
    enableFilePicker: true
}, viewerElement);

viewerElement.addEventListener('ready', function () {
    _this.iframeWindow = viewerElement.querySelector('iframe').contentWindow
    console.log(viewer.instance);
    console.log(viewer.getInstance());
});

When I try to get instance using .getInstance() method. It gives undefined when printed on console.

I would really appreciate your help.

Thanks,
Jay Rathod

WebViewer is null because the WebViewer runs in iframe and Salesforce doesn’t allow accessing iframe’s contentWindow. The WebViewer APIs are not accessible directly in Lightning Web Components (LWC), instead you need to use postMessage JavaScript API as Salesforce recommends. You can read this blog for examples https://www.pdftron.com/blog/webviewer/add-pdf-viewer-editor-to-salesforce-as-lwc/#communicating-with-corecontrols-from-lightning-web-component

Sardor Isakov
Software Developer
PDFTron Systems, Inc.