|
1 | | -import { Component, Input, Output, ViewChild, EventEmitter, ElementRef } from '@angular/core'; |
| 1 | +import { Component, Input, Output, OnInit, ViewChild, EventEmitter, ElementRef } from '@angular/core'; |
2 | 2 |
|
3 | 3 | @Component({ |
4 | 4 | selector: 'ng2-pdfjs-viewer', |
5 | 5 | template: `<iframe title="ng2-pdfjs-viewer" [hidden]="externalWindow || (!externalWindow && !pdfSrc)" #iframe width="100%" height="100%"></iframe>` |
6 | 6 | }) |
7 | | -export class PdfJsViewerComponent { |
| 7 | +export class PdfJsViewerComponent implements OnInit { |
8 | 8 | @ViewChild('iframe', { static: true }) iframe: ElementRef; |
9 | 9 | static lastID = 0; |
10 | 10 | @Input() public viewerId = `ng2-pdfjs-viewer-ID${++lastID}`; |
@@ -135,6 +135,7 @@ export class PdfJsViewerComponent { |
135 | 135 | this.loadPdf(); |
136 | 136 | } |
137 | 137 |
|
| 138 | + private relaseUrl?: () => void; // Avoid memory leask with `URL.createObjectURL` |
138 | 139 | private loadPdf() { |
139 | 140 | if (!this._src) { |
140 | 141 | return; |
@@ -180,15 +181,20 @@ export class PdfJsViewerComponent { |
180 | 181 | } |
181 | 182 | } |
182 | 183 |
|
| 184 | + this.relaseUrl?.(); |
183 | 185 | let fileUrl; |
184 | 186 | //if (typeof this.src === "string") { |
185 | 187 | // fileUrl = this.src; |
186 | 188 | //} |
187 | 189 | 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); |
189 | 193 | } else if (this._src instanceof Uint8Array) { |
190 | 194 | 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); |
192 | 198 | } else { |
193 | 199 | fileUrl = this._src; |
194 | 200 | } |
|
0 commit comments