diff --git a/Changelog.md b/Changelog.md index 6dc2107e..b2df37f8 100644 --- a/Changelog.md +++ b/Changelog.md @@ -9,6 +9,8 @@ - Fixed startup failure with host lockfile (#1125) @DYH1319 - Fixed hanging host when Electron exists before bridge (#1124) @DYH1319 - Fixed dev mode launches passing the script file instead of the app directory (#1121) @Denny09310 +- Added support for `WebContentsView` as an alternative to `BrowserWindow` (#1131) +- Added `window.electronNET.getPathForFile` to retrieve the path of dropped files in the renderer (#1002) # 0.6.0 diff --git a/docs/Using/File-Drop.md b/docs/Using/File-Drop.md new file mode 100644 index 00000000..4d6eda41 --- /dev/null +++ b/docs/Using/File-Drop.md @@ -0,0 +1,89 @@ +# Getting File Paths (File Drop) + +For security reasons, browsers do not expose the file system path of a `File` object, e.g., one obtained via drag and drop or an `` element. Electron provides [`webUtils.getPathForFile`](https://www.electronjs.org/docs/latest/api/web-utils#webutilsgetpathforfilefile) for this, but it is only accessible from a preload script. + +Electron.NET registers a small preload script for every session, which exposes this function as `window.electronNET.getPathForFile`. It works regardless of the `NodeIntegration`, `ContextIsolation`, and `Sandbox` settings of the window, and it runs side by side with your own `WebPreferences.Preload` script. + +`getPathForFile` returns an empty string for files that are not backed by the file system (e.g., created via `new File()`). + +## Plain JavaScript + +```html +
Drop files here
+ + +``` + +To process the paths in .NET, send them to the main process, e.g., via `ipcRenderer.send` (with node integration) and `Electron.IpcMain.On`, or post them to an endpoint of your ASP.NET Core app. + +## Blazor + +In Blazor, the `drop` event does not give you access to the `File` objects, so a small JavaScript helper is used to forward the paths to .NET: + +```javascript +// wwwroot/js/fileDrop.js +window.registerFileDrop = (element, dotNetRef) => { + element.addEventListener('dragover', (e) => e.preventDefault()); + element.addEventListener('drop', (e) => { + e.preventDefault(); + const paths = Array.from(e.dataTransfer.files) + .map((file) => window.electronNET.getPathForFile(file)) + .filter((path) => path); + dotNetRef.invokeMethodAsync('OnFilesDropped', paths); + }); +}; +``` + +```razor +@inject IJSRuntime JS +@implements IDisposable + +
Drop files here
+ + + +@code { + private ElementReference dropZone; + private DotNetObjectReference? selfRef; + private string[] paths = []; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + { + selfRef = DotNetObjectReference.Create(this); + await JS.InvokeVoidAsync("registerFileDrop", dropZone, selfRef); + } + } + + [JSInvokable] + public void OnFilesDropped(string[] droppedPaths) + { + paths = droppedPaths; + StateHasChanged(); + } + + public void Dispose() => selfRef?.Dispose(); +} +``` + +> [!NOTE] +> Dropping a file anywhere outside an element that calls `preventDefault()` on `dragover` / `drop` makes Electron navigate to that file. Handle these events on `document` if you want to prevent this globally. diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md index 28af3551..b01a222b 100644 --- a/docs/_Sidebar.md +++ b/docs/_Sidebar.md @@ -27,6 +27,7 @@ - [Package Building](Using/Package-Building.md) - [Secure Communication](Using/Secure-Communication.md) - [Adding a `custom_main.js`](Using/Custom_main.md) +- [File Paths (File Drop)](Using/File-Drop.md) # API Reference diff --git a/src/ElectronNET.Host/main.js b/src/ElectronNET.Host/main.js index 8aa91d4a..6fd54660 100644 --- a/src/ElectronNET.Host/main.js +++ b/src/ElectronNET.Host/main.js @@ -184,6 +184,28 @@ function getForwardedArgs() { const forwardedArgs = getForwardedArgs(); +// Register the Electron.NET host preload (exposing `window.electronNET`, e.g., with +// `getPathForFile` for file drops) on every session. Using session preloads instead of +// `webPreferences.preload` keeps user supplied preload scripts working side by side. +const hostPreloadPath = path.join(__dirname, 'scripts', 'host-preload.js'); +const sessionsWithHostPreload = new WeakSet(); + +function registerHostPreload(ses) { + if (!ses || sessionsWithHostPreload.has(ses)) { + return; + } + + sessionsWithHostPreload.add(ses); + + try { + ses.registerPreloadScript({ type: 'frame', filePath: hostPreloadPath }); + } catch (err) { + console.error('Could not register the Electron.NET host preload script:', err); + } +} + +app.on('session-created', registerHostPreload); + app.on('ready', () => { // Fix ERR_UNKNOWN_URL_SCHEME using file protocol // https://github.com/electron/electron/issues/23757 @@ -192,6 +214,9 @@ app.on('ready', () => { //// callback(pathname); ////}); + // the default session may have been created before the handler above was attached + registerHostPreload(require('electron').session.defaultSession); + if (isSplashScreenEnabled()) { startSplashScreen(); } diff --git a/src/ElectronNET.Host/scripts/host-preload.js b/src/ElectronNET.Host/scripts/host-preload.js new file mode 100644 index 00000000..fcd0bfc5 --- /dev/null +++ b/src/ElectronNET.Host/scripts/host-preload.js @@ -0,0 +1,25 @@ +// Electron.NET host preload script. +// Registered for every session (see main.js) and exposes a small set of +// renderer helpers as `window.electronNET` - independent of the +// nodeIntegration, contextIsolation and sandbox settings of the page. +const { contextBridge, webUtils } = require('electron'); + +const api = { + // Returns the absolute file system path of a File object, e.g., one + // obtained from a drop event (event.dataTransfer.files) or an + // element. Returns an empty string for files that + // are not backed by the file system (e.g., created via `new File()`). + getPathForFile(file) { + return webUtils.getPathForFile(file); + }, +}; + +try { + if (process.contextIsolated) { + contextBridge.exposeInMainWorld('electronNET', api); + } else { + window.electronNET = api; + } +} catch (err) { + console.error('Electron.NET: unable to expose renderer helpers', err); +}