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
5 changes: 4 additions & 1 deletion Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@
- 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)
- Added support for `WebContentsView` as an alternative to `BrowserWindow` (#1131)
- Added `Enum` converter to respect `EnumMemberAttributeenhancement` (#1132) @AeonSake
- Added support for file drop (#1134)
- Added `Session.SetDownloadPolicy` and events (`OnDownloadStarted`, `OnDownloadBlocked` and `OnDownloadDone`) to block or redirect downloads (#434)

# 0.6.0

Expand Down
19 changes: 19 additions & 0 deletions docs/API/WebContents.md
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,25 @@ webContents.OnMediaStartedPlaying += () => Console.WriteLine("Media playing");
webContents.OnMediaPaused += () => Console.WriteLine("Media paused");
```

### Controlling Downloads

`Session.SetDownloadPolicy` blocks downloads by file extension and can store allowed downloads in a fixed directory without a save dialog. The rules are evaluated inside the Electron host, so they apply to every download without a round trip to .NET. The policy belongs to the underlying Electron session, which by default is shared by all windows. Pass `null` to restore the default behavior.

```csharp
var session = browserWindow.WebContents.Session;

session.SetDownloadPolicy(new DownloadPolicy
{
BlockedExtensions = new[] { ".exe", ".msi", ".bat" },
// AllowedExtensions = new[] { ".pdf" }, // optional allow-list
SaveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"),
});

session.OnDownloadBlocked += info => Console.WriteLine($"Blocked {info.Filename}");
session.OnDownloadStarted += info => Console.WriteLine($"Saving {info.Filename} to {info.SavePath}");
session.OnDownloadDone += info => Console.WriteLine($"{info.Filename}: {info.State}");
```

## Related APIs

- [Electron.WindowManager](WindowManager.md) - Windows containing web contents
Expand Down
71 changes: 71 additions & 0 deletions src/ElectronNET.API/API/Entities/DownloadInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// Information about a download handled by a session.
/// </summary>
public class DownloadInfo
{
/// <summary>
/// The origin URL of the download.
/// </summary>
public string Url { get; set; }

/// <summary>
/// The file name suggested for the download.
/// </summary>
public string Filename { get; set; }

/// <summary>
/// The MIME type of the download.
/// </summary>
public string MimeType { get; set; }

/// <summary>
/// The total size of the download in bytes, or 0 if unknown.
/// </summary>
public long TotalBytes { get; set; }

/// <summary>
/// The path the download is saved to. Empty if it is not known yet, e.g. when the
/// user still has to pick a location in the save dialog.
/// </summary>
public string SavePath { get; set; }
}

/// <summary>
/// Information about a finished download.
/// </summary>
public class DownloadDoneInfo : DownloadInfo
{
/// <summary>
/// How the download ended.
/// </summary>
public DownloadDoneState State { get; set; }

/// <summary>
/// The number of bytes received.
/// </summary>
public long ReceivedBytes { get; set; }
}

/// <summary>
/// How a download ended (per the DownloadItem 'done' event).
/// </summary>
public enum DownloadDoneState
{
/// <summary>
/// The download finished successfully.
/// </summary>
Completed,

/// <summary>
/// The download was cancelled.
/// </summary>
Cancelled,

/// <summary>
/// The download was interrupted and cannot be resumed.
/// </summary>
Interrupted,
}
}
38 changes: 38 additions & 0 deletions src/ElectronNET.API/API/Entities/DownloadPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// Rules that decide how a session handles downloads. They are applied synchronously
/// inside Electron's 'will-download' event, so a download can be blocked or stored
/// without any round trip to .NET.
/// </summary>
public class DownloadPolicy
{
/// <summary>
/// File extensions that are never downloaded, e.g. ".exe" or ".tar.gz". Matching is
/// case-insensitive and the leading dot is optional. Takes precedence over
/// <see cref="AllowedExtensions"/>.
/// </summary>
public string[] BlockedExtensions { get; set; }

/// <summary>
/// If set and not empty, only files with one of these extensions are downloaded;
/// every other download is blocked. Matching is case-insensitive and the leading
/// dot is optional.
/// </summary>
public string[] AllowedExtensions { get; set; }

/// <summary>
/// If set, allowed downloads are stored in this directory without showing a save dialog.
/// The directory is created if it does not exist. If not set, Electron's default
/// behavior (usually a save dialog) is used.
/// </summary>
public string SaveDirectory { get; set; }

/// <summary>
/// Only used together with <see cref="SaveDirectory"/>. If false (default), a numeric
/// suffix is appended when a file with the same name already exists, e.g. "report (1).pdf".
/// If true, the existing file is overwritten.
/// </summary>
public bool Overwrite { get; set; }
}
}
123 changes: 123 additions & 0 deletions src/ElectronNET.API/API/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ internal Session(int id)
Id = id;
Cookies = new Cookies(id);
WebRequest = new WebRequest(id);
_downloadStarted = new DownloadEvent<DownloadInfo>(id, "started");
_downloadBlocked = new DownloadEvent<DownloadInfo>(id, "blocked");
_downloadDone = new DownloadEvent<DownloadDoneInfo>(id, "done");
}

/// <summary>
Expand Down Expand Up @@ -144,6 +147,126 @@ public void CreateInterruptedDownload(CreateInterruptedDownloadOptions options)
BridgeConnector.Socket.Emit("webContents-session-createInterruptedDownload", Id, options);
}

/// <summary>
/// Sets the rules that decide how this session handles downloads, e.g. to block
/// certain file extensions or to store downloads in a directory without showing
/// a save dialog. The rules are evaluated synchronously in the Electron host, so
/// they take effect for every download. Pass null to restore Electron's default
/// behavior.
/// <para>
/// The policy belongs to the underlying Electron session, which by default is shared
/// by all windows.
/// </para>
/// </summary>
/// <param name="policy">The download rules, or null to remove them.</param>
public void SetDownloadPolicy(DownloadPolicy policy)
{
BridgeConnector.Socket.Emit("webContents-session-setDownloadPolicy", Id, policy);
}

/// <summary>
/// Emitted when a download that is allowed by the <see cref="DownloadPolicy"/>
/// (or any download, if no policy is set) starts.
/// </summary>
public event Action<DownloadInfo> OnDownloadStarted
{
add => _downloadStarted.Add(value);
remove => _downloadStarted.Remove(value);
}

/// <summary>
/// Emitted when a download was blocked by the <see cref="DownloadPolicy"/>.
/// </summary>
public event Action<DownloadInfo> OnDownloadBlocked
{
add => _downloadBlocked.Add(value);
remove => _downloadBlocked.Remove(value);
}

/// <summary>
/// Emitted when a download has completed, was cancelled or was interrupted.
/// </summary>
public event Action<DownloadDoneInfo> OnDownloadDone
{
add => _downloadDone.Add(value);
remove => _downloadDone.Remove(value);
}

private readonly DownloadEvent<DownloadInfo> _downloadStarted;
private readonly DownloadEvent<DownloadInfo> _downloadBlocked;
private readonly DownloadEvent<DownloadDoneInfo> _downloadDone;

/// <summary>
/// Keeps the .NET handlers of one download event and its bridge registration in sync.
/// Handler changes and (un)registration happen under one lock, so a concurrent
/// subscribe can never end up without a socket listener or host subscription.
/// </summary>
private sealed class DownloadEvent<T>
{
private readonly object _lock = new object();
private readonly int _id;
private readonly string _kind;
private Action<T> _handlers;

public DownloadEvent(int id, string kind)
{
_id = id;
_kind = kind;
}

private string EventName => $"webContents-session-download-{_kind}{_id}";

public void Add(Action<T> value)
{
if (value == null)
{
return;
}

lock (_lock)
{
if (_handlers == null)
{
BridgeConnector.Socket.On<T>(EventName, Invoke);
BridgeConnector.Socket.Emit("register-webContents-session-download", _id, _kind);
}

_handlers += value;
}
}

public void Remove(Action<T> value)
{
lock (_lock)
{
if (_handlers == null)
{
return;
}

_handlers -= value;

if (_handlers == null)
{
BridgeConnector.Socket.Off(EventName);
BridgeConnector.Socket.Emit("unregister-webContents-session-download", _id, _kind);
}
}
}

private void Invoke(T info)
{
Action<T> handlers;

lock (_lock)
{
handlers = _handlers;
}

handlers?.Invoke(info);
}
}

/// <summary>
/// Disables any network emulation already active for the session. Resets to the
/// original network configuration.
Expand Down
Loading