| 1 | |
| 2 | |
| 3 | export class PrivateBrowser { |
| 4 | constructor(cdp, downloadPath) { |
| 5 | this.cdp = cdp; |
| 6 | this.downloadPath = downloadPath; |
| 7 | this.context = ""; |
| 8 | } |
| 9 | |
| 10 | tab(raw) { |
| 11 | return { ...raw, incognito: Boolean(this.context && raw.browserContextId === this.context) }; |
| 12 | } |
| 13 | |
| 14 | async open(url, activate) { |
| 15 | await this.prune(); |
| 16 | if (!this.context) { |
| 17 | const { browserContextId } = await this.cdp("Target.createBrowserContext", { disposeOnDetach: true }); |
| 18 | this.context = browserContextId; |
| 19 | } |
| 20 | try { |
| 21 | await this.cdp("Browser.setDownloadBehavior", { |
| 22 | browserContextId: this.context, behavior: "allowAndName", |
| 23 | downloadPath: this.downloadPath, eventsEnabled: true, |
| 24 | }); |
| 25 | const { targetId } = await this.cdp("Target.createTarget", { |
| 26 | browserContextId: this.context, url, newWindow: true, |
| 27 | }); |
| 28 | await activate(this.tab({ targetId, browserContextId: this.context, type: "page", url })); |
| 29 | return { id: targetId, incognito: true }; |
| 30 | } catch (error) { |
| 31 | await this.prune(); |
| 32 | throw error; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | async prune() { |
| 37 | if (!this.context) return; |
| 38 | const { targetInfos } = await this.cdp("Target.getTargets"); |
| 39 | if (targetInfos.some(tab => tab.type === "page" && tab.browserContextId === this.context)) return; |
| 40 | await this.cdp("Target.disposeBrowserContext", { browserContextId: this.context }); |
| 41 | this.context = ""; |
| 42 | } |
| 43 | } |