Skip to content

Commit 45f2a87

Browse files
authored
Merge pull request #224 from Akxe/fix-memory-leak
Fix memory leak
2 parents 034164d + cd32e60 commit 45f2a87

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

lib/src/ng2-pdfjs-viewer.component.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { Component, Input, Output, ViewChild, EventEmitter, ElementRef } from '@angular/core';
1+
import { Component, Input, Output, OnInit, ViewChild, EventEmitter, ElementRef } from '@angular/core';
22

33
@Component({
44
selector: 'ng2-pdfjs-viewer',
55
template: `<iframe title="ng2-pdfjs-viewer" [hidden]="externalWindow || (!externalWindow && !pdfSrc)" #iframe width="100%" height="100%"></iframe>`
66
})
7-
export class PdfJsViewerComponent {
7+
export class PdfJsViewerComponent implements OnInit {
88
@ViewChild('iframe', { static: true }) iframe: ElementRef;
99
static lastID = 0;
1010
@Input() public viewerId = `ng2-pdfjs-viewer-ID${++lastID}`;
@@ -135,6 +135,7 @@ export class PdfJsViewerComponent {
135135
this.loadPdf();
136136
}
137137

138+
private relaseUrl?: () => void; // Avoid memory leask with `URL.createObjectURL`
138139
private loadPdf() {
139140
if (!this._src) {
140141
return;
@@ -180,15 +181,20 @@ export class PdfJsViewerComponent {
180181
}
181182
}
182183

184+
this.relaseUrl?.();
183185
let fileUrl;
184186
//if (typeof this.src === "string") {
185187
// fileUrl = this.src;
186188
//}
187189
if (this._src instanceof Blob) {
188-
fileUrl = encodeURIComponent(URL.createObjectURL(this._src));
190+
const url = URL.createObjectURL(this._src);
191+
fileUrl = encodeURIComponent(url);
192+
this.relaseUrl = () => URL.revokeObjectURL(url);
189193
} else if (this._src instanceof Uint8Array) {
190194
let blob = new Blob([this._src], { type: "application/pdf" });
191-
fileUrl = encodeURIComponent(URL.createObjectURL(blob));
195+
const url = createObjectURL(blob);
196+
this.relaseUrl = () => URL.revokeObjectURL(url);
197+
fileUrl = encodeURIComponent(url);
192198
} else {
193199
fileUrl = this._src;
194200
}

0 commit comments

Comments
 (0)