webviewer.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const ComPDFKitViewer = {
  2. init (options, element, optionsUrl) {
  3. return new Promise((resolve) => {
  4. element.addEventListener("ready", function ready () {
  5. element.removeEventListener('ready', ready)
  6. const iframeWindow = element.querySelector('iframe').contentWindow
  7. Promise.resolve().then(function() {
  8. resolve({
  9. docViewer: iframeWindow.instance
  10. })
  11. })
  12. })
  13. const viewer = new Viewer(options, element, optionsUrl)
  14. })
  15. }
  16. }
  17. class Viewer {
  18. constructor (options, element, optionsUrl) {
  19. this.instance = null
  20. this.initialDoc = options.initialDoc || null
  21. this.element = element
  22. element.addEventListener("ready", (function ready() {
  23. element.removeEventListener("ready", ready)
  24. }))
  25. this.create()
  26. }
  27. _createEvent (e, t) {
  28. let n;
  29. try {
  30. n = new CustomEvent(e, {
  31. detail: t,
  32. bubbles: true,
  33. cancelable: true
  34. })
  35. } catch (o) {
  36. (n = document.createEvent("Event")).initEvent(e, true, true),
  37. n.detail = t
  38. }
  39. return n
  40. }
  41. create() {
  42. if (this.initialDoc) {
  43. this.initialDoc = encodeURIComponent(this.initialDoc)
  44. this._create()
  45. } else {
  46. this._create()
  47. }
  48. }
  49. _create () {
  50. if (!this._trigger) {
  51. this._trigger = function(e, t) {
  52. var n = this._createEvent(e, t);
  53. this.element.dispatchEvent(n)
  54. }
  55. }
  56. this.createViewer()
  57. }
  58. createViewer () {
  59. const self = this
  60. let webviewerUrl = './webviewer/index.html'
  61. if (this.initialDoc) {
  62. webviewerUrl += "#d=\"".concat(decodeURIComponent(this.initialDoc)).concat("\"")
  63. }
  64. const iframe = document.createElement("iframe")
  65. iframe.id = "webviewer-".concat(this.id)
  66. iframe.src = webviewerUrl
  67. iframe.title = "webviewer"
  68. iframe.frameBorder = 0
  69. iframe.width = "100%"
  70. iframe.height = "100%"
  71. iframe.setAttribute("allowfullscreen", true)
  72. iframe.setAttribute("webkitallowfullscreen", true)
  73. iframe.setAttribute("mozallowfullscreen", true)
  74. this.iframe = iframe
  75. this.options?.backgroundColor && iframe.setAttribute("data-bgcolor", this.options.backgroundColor),
  76. this.options?.assetPath && iframe.setAttribute("data-assetpath", encodeURIComponent(this.options.assetPath)),
  77. this.loadListener = function() {
  78. var $iframe = self.iframe;
  79. self.instance = $iframe.contentWindow.instance;
  80. self._trigger("ready");
  81. },
  82. iframe.addEventListener("load", this.loadListener),
  83. this.element.appendChild(iframe)
  84. }
  85. }
  86. export default ComPDFKitViewer