Search code examples
javascriptopenseadragon

Get reference to existing OpenSeadragon Viewer


I need to add an overlay to an existing OpenSeadragon viewer object which isn't created by my code, but elsewhere in the application.

I have got to a point where I know that the viewer has been created as I can access the various html elements that are created via jQuery. However I can't work out if there's any way to create a viewer from an existing reference.

I've tried using the id of the viewer div in:

var viewer = OpenSeadragon(id: "open-seadragon-viewer-id");

but this doesn't seem to work.

Is there any way to do this or can you only get the viewer within the code that initialised it?


Solution

  • Here's one crazy thought... you could monkey-patch some portion of OSD in order to grab the viewer...

    var viewer;
    var originalIsOpen = OpenSeadragon.Viewer.prototype.isOpen;
    
    OpenSeadragon.Viewer.prototype.isOpen = function() {
      // Now we know the viewer!
      viewer = this;
      
      // Reinstate the original, since we only need to run our version once
      OpenSeadragon.Viewer.prototype.isOpen = originalIsOpen;
      
      // Call the original
      return originalIsOpen.call(this);
    }
    

    It's kind of tacky, but should work. Note this assumes there is only one viewer on the page... if there are more than one, the same principle could work but you would need to keep track of an array of viewers.

    BTW, I'm using isOpen, because it's simple and it gets called every frame. Other functions could work as well.

    EDIT: fixed code so we are using the prototype. I still haven't actually tested this code so there may still be bugs!