From ce84bf5a431b0499f9a0e003b6087194a97b98b7 Mon Sep 17 00:00:00 2001 From: Adam Eisenreich Date: Mon, 22 May 2023 12:29:38 +0200 Subject: [PATCH] Fix: Memory leak on every change of source --- lib/src/ng2-pdfjs-viewer.component.ts | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/lib/src/ng2-pdfjs-viewer.component.ts b/lib/src/ng2-pdfjs-viewer.component.ts index a578d30d..2077dd3a 100644 --- a/lib/src/ng2-pdfjs-viewer.component.ts +++ b/lib/src/ng2-pdfjs-viewer.component.ts @@ -1,10 +1,10 @@ -import { Component, Input, Output, ViewChild, EventEmitter, ElementRef } from '@angular/core'; +import { Component, Input, Output, OnInit, ViewChild, EventEmitter, ElementRef } from '@angular/core'; @Component({ selector: 'ng2-pdfjs-viewer', template: `` }) -export class PdfJsViewerComponent { +export class PdfJsViewerComponent implements OnInit { @ViewChild('iframe', {static: true}) iframe: ElementRef; @Input() public viewerId: string; @Output() onBeforePrint: EventEmitter = new EventEmitter(); @@ -40,12 +40,12 @@ export class PdfJsViewerComponent { @Input() public errorAppend: boolean = true; @Input() public errorMessage: string; @Input() public diagnosticLogs: boolean = true; - + @Input() public externalWindowOptions: string; public viewerTab: any; private _src: string | Blob | Uint8Array; private _page: number; - + @Input() public set page(_page: number) { this._page = _page; @@ -134,6 +134,7 @@ export class PdfJsViewerComponent { this.loadPdf(); } + private relaseUrl?: () => void; // Avoid memory leask with `URL.createObjectURL` private loadPdf() { if (!this._src) { return; @@ -179,15 +180,20 @@ export class PdfJsViewerComponent { } } + this.relaseUrl?.(); let fileUrl; //if (typeof this.src === "string") { // fileUrl = this.src; //} if (this._src instanceof Blob) { - fileUrl = encodeURIComponent(URL.createObjectURL(this._src)); + const url = URL.createObjectURL(this._src); + fileUrl = encodeURIComponent(url); + this.relaseUrl = () => URL.revokeObjectURL(url); } else if (this._src instanceof Uint8Array) { let blob = new Blob([this._src], { type: "application/pdf" }); - fileUrl = encodeURIComponent(URL.createObjectURL(blob)); + const url = createObjectURL(blob); + this.relaseUrl = () => URL.revokeObjectURL(url); + fileUrl = encodeURIComponent(url); } else { fileUrl = this._src; } @@ -274,7 +280,7 @@ export class PdfJsViewerComponent { if (this.useOnlyCssZoom) { viewerUrl += `&useOnlyCssZoom=${this.useOnlyCssZoom}`; } - + if (this._page || this.zoom || this.nameddest || this.pagemode) viewerUrl += "#" if (this._page) { viewerUrl += `&page=${this._page}`; @@ -334,4 +340,4 @@ export class PdfJsViewerComponent { // pagemode = ${this.errorMessage} // `); } -} \ No newline at end of file +}