Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
89 changes: 89 additions & 0 deletions docs/Using/File-Drop.md
Original file line number Diff line number Diff line change
@@ -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 `<input type="file">` 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
<div id="drop-zone">Drop files here</div>

<script>
const dropZone = document.getElementById('drop-zone');

dropZone.addEventListener('dragover', (e) => e.preventDefault());

dropZone.addEventListener('drop', (e) => {
e.preventDefault();

for (const file of e.dataTransfer.files) {
const path = window.electronNET.getPathForFile(file);
console.log(path);
}
});
</script>
```

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

<div @ref="dropZone" class="drop-zone">Drop files here</div>

<ul>
@foreach (var path in paths)
{
<li>@path</li>
}
</ul>

@code {
private ElementReference dropZone;
private DotNetObjectReference<FileDropZone>? 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.
1 change: 1 addition & 0 deletions docs/_Sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
25 changes: 25 additions & 0 deletions src/ElectronNET.Host/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();
}
Expand Down
25 changes: 25 additions & 0 deletions src/ElectronNET.Host/scripts/host-preload.js
Original file line number Diff line number Diff line change
@@ -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
// <input type="file"> 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);
}