diff --git a/index.d.ts b/index.d.ts index 34c186c..26977c4 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,4 +1,4 @@ -import {BrowserWindow, DownloadItem} from 'electron'; +import {BrowserView, BrowserWindow, DownloadItem} from 'electron'; declare namespace electronDl { interface Progress { @@ -121,7 +121,7 @@ declare const electronDl: { ``` */ download( - window: BrowserWindow, + window: BrowserWindow | BrowserView, url: string, options?: electronDl.Options ): Promise; diff --git a/index.js b/index.js index 8ff6421..5129887 100644 --- a/index.js +++ b/index.js @@ -15,6 +15,39 @@ const getFilenameFromMime = (name, mime) => { return `${name}.${extensions[0].ext}`; }; +const majorElectronVersion = () => { + const version = process.versions.electron.split('.'); + return parseInt(version[0], 10); +}; + +const getWindowFromBrowserView = webContents => { + for (const currentWindow of BrowserWindow.getAllWindows()) { + for (const currentBrowserView of currentWindow.getBrowserViews()) { + if (currentBrowserView.webContents.id === webContents.id) { + return currentWindow; + } + } + } +}; + +const getWindowFromWebContents = webContents => { + let window_; + const webContentsType = webContents.getType(); + switch (webContentsType) { + case 'webview': + window_ = BrowserWindow.fromWebContents(webContents.hostWebContents); + break; + case 'browserView': + window_ = getWindowFromBrowserView(webContents); + break; + default: + window_ = BrowserWindow.fromWebContents(webContents); + break; + } + + return window_; +}; + function registerListener(session, options, callback = () => {}) { const downloadItems = new Set(); let receivedBytes = 0; @@ -32,12 +65,7 @@ function registerListener(session, options, callback = () => {}) { downloadItems.add(item); totalBytes += item.getTotalBytes(); - let hostWebContents = webContents; - if (webContents.getType() === 'webview') { - ({hostWebContents} = webContents); - } - - const window_ = BrowserWindow.fromWebContents(hostWebContents); + const window_ = majorElectronVersion() >= 12 ? BrowserWindow.fromWebContents(webContents) : getWindowFromWebContents(webContents); const directory = options.directory || app.getPath('downloads'); let filePath; diff --git a/readme.md b/readme.md index 29e6f09..3131f4e 100644 --- a/readme.md +++ b/readme.md @@ -8,6 +8,7 @@ - Saves the file to the users Downloads directory instead of prompting. - Bounces the Downloads directory in the dock when done. *(macOS)* - Handles multiple downloads. +- Support for `BrowserWindow` and `BrowserView`. - Shows badge count *(macOS & Linux only)* and download progress. Example on macOS: @@ -63,9 +64,9 @@ It can only be used in the [main](https://electronjs.org/docs/glossary/#main-pro ### window -Type: `BrowserWindow` +Type: `BrowserWindow | BrowserView` -Window to register the behavior on. +Window to register the behavior on. Alternatively, a `BrowserView` can be passed. ### url