Hosting WebViewer files on a different domain

342 views
Skip to first unread message

Matt Parizeau

unread,
May 17, 2018, 5:25:11 PM5/17/18
to PDFTron WebViewer
Q:

Is it possible to host the WebViewer files, e.g. ReaderControl.html and everything in the iframe, on a different server from our web app?
domain1.com/myapp.html - call new PDFTron.WebViewer here
mycdn.com/lib/html5/... - host WebViewer files here

A:

Yes this is possible with some restrictions. You can set the path option in the PDFTron.WebViewer constructor to the location on the other server where you host the WebViewer files.

Because of browser cross domain policies you won't be able to call functions directly on the WebViewer instance (e.g. myWebViewer.setCurrentPageNumber(2)) because this works by accessing objects on the window of the iframe. If you have customizations inside a config file then these will work as expected because they're actually executed in the context of the iframe so there is no cross origin issue.

If you do have any code calling functions on the WebViewer instance it should definitely be possible to move it into a config file or the alternative is to use the Window.postMessage API to send messages between your app and the config file as this will work in a cross domain scenario.

For example you would have the following code in your app that creates the PDFTron.WebViewer constructor:
window.addEventListener('message', function(event) {
 
if (typeof event.data === 'object' && event.data.type === 'documentLoaded') {
   
// once the document loaded event is received we can tell the viewer to set the page number
   
event.source.postMessage({
      type
: 'setCurrentPageNumber',
      value
: 3
   
}, '*');
 
}
});

And this code in your config file:
window.addEventListener('message', function(event) {
 
if (typeof event.data === 'object' && event.data.type === 'setCurrentPageNumber') {
   
var pageNumber = event.data.value;
    readerControl
.setCurrentPageNumber(pageNumber);
 
}
});

// notify parent that config is ready to accept events
window
.parent.postMessage({ type: 'configReady' }, '*');

$
(document).on('documentLoaded', function() {
 
// notify parent that the document has loaded
  window
.parent.postMessage({ type: 'documentLoaded' }, '*');
});


Currently you get this to work you'll need to use the attached WebViewer.min.js file that has a few modifications from the current one in 3.2. The changes to this file will be included in future releases.
WebViewer.js.zip
Reply all
Reply to author
Forward
0 new messages