diff --git a/__test__/declarations.test.mjs b/__test__/declarations.test.mjs
index 8c08245..7f39a64 100644
--- a/__test__/declarations.test.mjs
+++ b/__test__/declarations.test.mjs
@@ -18,6 +18,28 @@ test('generated NAPI declarations compile without skipping library checks', () =
assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
});
+test('webview drag-drop events have typed payloads and keep window file events', () => {
+ const result = spawnSync(
+ process.execPath,
+ [
+ tsc,
+ '--noEmit',
+ '--skipLibCheck',
+ 'false',
+ '--target',
+ 'ESNext',
+ '--module',
+ 'commonjs',
+ '--moduleResolution',
+ 'node',
+ resolve(repoRoot, '__test__/types/native-file-drop.ts'),
+ ],
+ { cwd: repoRoot, encoding: 'utf8' },
+ );
+
+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);
+});
+
test('Application exposes the dock icon APIs with Buffer input', () => {
const declarations = readFileSync(resolve(repoRoot, 'js-bindings.d.ts'), 'utf8');
diff --git a/__test__/types/native-file-drop.ts b/__test__/types/native-file-drop.ts
new file mode 100644
index 0000000..872e6fa
--- /dev/null
+++ b/__test__/types/native-file-drop.ts
@@ -0,0 +1,57 @@
+import type {
+ BrowserWindowEventMap,
+ Webview,
+ WebviewDragDropEvent,
+ WebviewDragEnterEvent,
+ WebviewDragLeaveEvent,
+ WebviewDragOverEvent,
+ WebviewOptions,
+} from '../../index.js';
+
+declare const webview: Webview;
+
+webview.on('drag-enter', (event) => {
+ const name: 'drag-enter' = event.event;
+ const path: string = event.paths[0] ?? '';
+ const x: number = event.position.x;
+ const y: number = event.position.y;
+ void [name, path, x, y];
+});
+
+webview.on('drag-over', (event) => {
+ const name: 'drag-over' = event.event;
+ const x: number = event.position.x;
+ const y: number = event.position.y;
+ void [name, x, y];
+});
+
+webview.on('drag-drop', (event) => {
+ const name: 'drag-drop' = event.event;
+ const paths: string[] = event.paths;
+ const x: number = event.position.x;
+ const y: number = event.position.y;
+ void [name, paths, x, y];
+});
+
+webview.on('drag-leave', (event) => {
+ const name: 'drag-leave' = event.event;
+ void name;
+});
+
+const options: WebviewOptions = { nativeFileDrop: true };
+const windowDrop: BrowserWindowEventMap['file-drop'] = { event: 'file-drop', files: ['/tmp/file.txt'] };
+const enter: WebviewDragEnterEvent = {
+ event: 'drag-enter',
+ paths: ['/tmp/file.txt', '/tmp/folder'],
+ position: { x: 12, y: 34 },
+};
+const over: WebviewDragOverEvent = { event: 'drag-over', position: { x: 12, y: 34 } };
+const drop: WebviewDragDropEvent = { event: 'drag-drop', paths: ['/tmp/folder'], position: { x: 12, y: 34 } };
+const leave: WebviewDragLeaveEvent = { event: 'drag-leave' };
+
+// @ts-expect-error drag-enter requires paths
+const invalidEnter: WebviewDragEnterEvent = { event: 'drag-enter', position: { x: 0, y: 0 } };
+// @ts-expect-error drag-leave has no position
+const invalidLeave: WebviewDragLeaveEvent = { event: 'drag-leave', position: { x: 0, y: 0 } };
+
+void [options, windowDrop, enter, over, drop, leave, invalidEnter, invalidLeave];
diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md
index 03d94f8..544f2be 100644
--- a/docs/api/browser-window.md
+++ b/docs/api/browser-window.md
@@ -343,6 +343,11 @@ win.on('ime', ({ text, phase }) => { … })
win.on('touch', ({ x, y, touchId, phase }) => { … })
```
+`file-hover` and `file-drop` are window-level events. A webview can opt in to
+its own native file drop events with `nativeFileDrop: true`; those events are
+emitted by the `Webview` instance and are not forwarded to the window. See the
+[Webview native file drag-and-drop API](./webview.md#native-file-drag-and-drop).
+
The `close` event is cancelable. Call `event.preventDefault()` synchronously
to keep the native window, its webviews, and their browser context alive. A
close event without prevention follows the normal disposal path. The event
diff --git a/docs/api/webview.md b/docs/api/webview.md
index 16cf13a..407c307 100644
--- a/docs/api/webview.md
+++ b/docs/api/webview.md
@@ -27,9 +27,15 @@ interface WebviewOptions {
navigationHandler?: (url: string) => boolean; // allow or cancel navigation
newWindowHandler?: (event: WebviewNewWindowEvent) => boolean; // allow or cancel new windows
enableDragRegionHelpers?: boolean; // default: true; drag regions and window.webviewjs
+ nativeFileDrop?: boolean; // default: false; receive native file/folder drops
}
```
+`nativeFileDrop` is opt-in. When enabled, Wry installs a native drag-and-drop
+handler for this webview and emits `drag-enter`, `drag-over`, `drag-drop`, and
+`drag-leave`. When omitted or `false`, no native webview handler is registered,
+so the webview keeps its normal HTML5 drag-and-drop behavior.
+
> **Note on bounds:** For top-level webviews (not child), omit `x`/`y`/`width`/`height` so the webview fills the window and resizes with it automatically. Setting explicit bounds fixes the size, which causes the black-border artifact when the window is maximised.
## Navigation
@@ -80,6 +86,55 @@ request. Download events are observational and do not cancel downloads.
See the runnable [webview events example](../../examples/webview-events.mjs).
+### Native file drag-and-drop
+
+```js
+const webview = win.createWebview({ url: 'https://example.com', nativeFileDrop: true });
+
+webview.on('drag-enter', ({ paths, position }) => console.log(paths, position));
+webview.on('drag-over', ({ position }) => console.log(position));
+webview.on('drag-drop', ({ paths, position }) => console.log(paths, position));
+webview.on('drag-leave', () => console.log('Drag left webview'));
+```
+
+`drag-enter` and `drag-drop` include every file or directory path supplied by
+Wry. `drag-over` includes only the current position. `drag-leave` has no paths
+or position. Positions use the coordinate system reported by Wry and are
+relative to the webview's top-left corner; WebviewJS does not convert them to
+window or CSS coordinates. These are observational events sent
+through the webview's EventEmitter; they do not run JavaScript synchronously
+inside the native drag callback.
+
+These webview events are separate from the `BrowserWindow`'s `file-hover` and
+`file-drop` events. The window events continue to report drops handled by the
+window-level target, such as drops over the title bar. A native webview drop is
+reported on that `Webview` instance and is not re-emitted on its parent window.
+See [BrowserWindow events](./browser-window.md#events) for the existing
+window-level API.
+
+With Wry 0.55.1, the handler is available on Windows, macOS, and Linux. On
+Windows, Wry replaces WebView2's external file drop target while this option is
+enabled; WebView2's normal HTML5 file-drop handling, including drops onto
+``, is not preserved. Windows ignores Wry's handler return
+value. On macOS and Linux, this implementation returns `true` to Wry to consume
+the native drop; Wry documents that consuming the drop prevents drops onto
+``. Disable `nativeFileDrop` when the page needs its normal
+HTML5 file-drop behavior. This API does not resolve paths from DOM `File`
+objects.
+
+#### Manual platform verification
+
+Run `node examples/native-file-drop.mjs` on Windows, macOS, or Linux. Drag a
+file and a directory, including a multi-item selection, over the page and
+confirm that `drag-enter` and `drag-drop` report all paths and webview-relative
+positions, `drag-over` updates the position, and dragging outside the view emits
+`drag-leave`. Then try the example with `nativeFileDrop: false` and confirm no
+native webview events arrive and the page retains normal HTML5 handling. To
+check compatibility, drop an item over the window title bar and confirm the
+existing `BrowserWindow` `file-hover` / `file-drop` events still report it.
+On Windows, also verify that file drops onto an HTML `` are unavailable
+while native handling is enabled.
+
`HeaderData`:
```ts
diff --git a/examples/native-file-drop.mjs b/examples/native-file-drop.mjs
new file mode 100644
index 0000000..374eadc
--- /dev/null
+++ b/examples/native-file-drop.mjs
@@ -0,0 +1,40 @@
+import { Application } from '../index.js';
+
+const app = new Application();
+const window = app.createBrowserWindow({
+ title: 'Native webview file drop',
+ width: 900,
+ height: 600,
+});
+
+const webview = window.createWebview({
+ nativeFileDrop: true,
+ html: `
+
+
+
+ Native webview file drop
+
+
+
+
+
Drop files or folders here
+
Native paths and webview-relative positions are logged in the terminal.
+
+
+
+ `,
+});
+
+webview.on('drag-enter', ({ paths, position }) => console.log('webview drag-enter', { paths, position }));
+webview.on('drag-over', ({ position }) => console.log('webview drag-over', { position }));
+webview.on('drag-drop', ({ paths, position }) => console.log('webview drag-drop', { paths, position }));
+webview.on('drag-leave', () => console.log('webview drag-leave'));
+
+window.on('file-hover', ({ files }) => console.log('window file-hover', { files }));
+window.on('file-drop', ({ files }) => console.log('window file-drop', { files }));
+
+app.run();
diff --git a/index.d.ts b/index.d.ts
index 88780aa..9c034d1 100644
--- a/index.d.ts
+++ b/index.d.ts
@@ -168,6 +168,32 @@ export interface WebviewNewWindowEvent {
windowFeatures?: import('./js-bindings').WebviewNewWindowFeatures;
}
+export interface WebviewDragPosition {
+ x: number;
+ y: number;
+}
+
+export interface WebviewDragEnterEvent {
+ event: 'drag-enter';
+ paths: string[];
+ position: WebviewDragPosition;
+}
+
+export interface WebviewDragOverEvent {
+ event: 'drag-over';
+ position: WebviewDragPosition;
+}
+
+export interface WebviewDragDropEvent {
+ event: 'drag-drop';
+ paths: string[];
+ position: WebviewDragPosition;
+}
+
+export interface WebviewDragLeaveEvent {
+ event: 'drag-leave';
+}
+
/** Maps Webview event names to their typed payloads. */
export interface WebviewEventMap {
'page-load-started': WebviewPageLoadEvent;
@@ -183,6 +209,10 @@ export interface WebviewEventMap {
* separate WebView2 thread.
*/
'new-window': WebviewNewWindowEvent;
+ 'drag-enter': WebviewDragEnterEvent;
+ 'drag-over': WebviewDragOverEvent;
+ 'drag-drop': WebviewDragDropEvent;
+ 'drag-leave': WebviewDragLeaveEvent;
}
export interface WindowMoveEvent {
@@ -293,6 +323,12 @@ declare module './js-bindings' {
}
interface WebviewOptions {
+ /**
+ * Enable native file drag-and-drop events on the webview. Defaults to false.
+ * When enabled, native handling consumes drops where supported and can replace the
+ * platform webview's normal HTML5 file-drop behavior.
+ */
+ nativeFileDrop?: boolean;
/**
* Shared `WebContext` for cookie/data isolation across webviews.
* Create one with `app.createWebContext({ dataDirectory })` and pass it here.
diff --git a/js-bindings.d.ts b/js-bindings.d.ts
index f462c16..aa7c82e 100644
--- a/js-bindings.d.ts
+++ b/js-bindings.d.ts
@@ -660,6 +660,10 @@ export interface WebviewEventPayload {
title?: string;
/** Download success flag for `DownloadCompleted` events. */
success?: boolean;
+ /** Paths for native webview drag-enter and drag-drop events. */
+ paths?: Array;
+ /** Drag position relative to the webview's top-left corner. */
+ position?: WebviewWindowPosition;
}
export type WebviewEventThreadsafeFunction = (err: Error | null, arg: WebviewEventPayload) => void;
@@ -677,6 +681,10 @@ export declare enum WebviewEventType {
* (`window.open`, `target="_blank"`, etc.).
*/
NewWindowRequested = 6,
+ DragEnter = 7,
+ DragOver = 8,
+ DragDrop = 9,
+ DragLeave = 10,
}
/** Optional size and position hints supplied for a new-window request. */
@@ -715,6 +723,8 @@ export interface WebviewOptions {
useHttpsScheme?: boolean;
/** Whether to inject the drag support: the helper that starts a native window drag from elements marked with `data-webview-drag-region`, and `window.webviewjs.startDragging()` (default: true). */
enableDragRegionHelpers?: boolean;
+ /** Whether to receive native file drag-and-drop events on this webview (default: false). */
+ nativeFileDrop?: boolean;
}
export type WebviewScriptThreadsafeFunction = (err: Error | null, arg: string) => void;
diff --git a/src/types.rs b/src/types.rs
index 3470386..289800b 100644
--- a/src/types.rs
+++ b/src/types.rs
@@ -475,6 +475,10 @@ pub enum WebviewEventType {
/// Fired when a page attempts to open a new browser window
/// (`window.open`, `target="_blank"`, etc.).
NewWindowRequested,
+ DragEnter,
+ DragOver,
+ DragDrop,
+ DragLeave,
}
impl WebviewEventType {
@@ -487,6 +491,10 @@ impl WebviewEventType {
Self::DownloadCompleted => "download-completed",
Self::NavigationStarted => "navigation",
Self::NewWindowRequested => "new-window",
+ Self::DragEnter => "drag-enter",
+ Self::DragOver => "drag-over",
+ Self::DragDrop => "drag-drop",
+ Self::DragLeave => "drag-leave",
}
}
}
@@ -506,6 +514,10 @@ pub struct WebviewEventPayload {
pub title: Option,
/// Download success flag for `DownloadCompleted` events.
pub success: Option,
+ /// Paths for native webview drag-enter and drag-drop events.
+ pub paths: Option>,
+ /// Drag position relative to the webview's top-left corner.
+ pub position: Option,
}
/// Optional size and position hints supplied for a new-window request.
@@ -559,4 +571,6 @@ pub struct WebviewOptions {
pub use_https_scheme: Option,
/// Whether to inject the drag support: the helper that starts a native window drag from elements marked with `data-webview-drag-region`, and `window.webviewjs.startDragging()` (default: true).
pub enable_drag_region_helpers: Option,
+ /// Whether to receive native file drag-and-drop events on this webview (default: false).
+ pub native_file_drop: Option,
}
diff --git a/src/webview.rs b/src/webview.rs
index 5eaaa13..bacdbcf 100644
--- a/src/webview.rs
+++ b/src/webview.rs
@@ -15,7 +15,8 @@ use napi_derive::*;
use std::sync::Arc;
use tao::window::Window;
use wry::{
- http::Request, NewWindowFeatures, NewWindowResponse, PageLoadEvent, Rect, WebViewBuilder,
+ http::Request, DragDropEvent, NewWindowFeatures, NewWindowResponse, PageLoadEvent, Rect,
+ WebViewBuilder,
};
use crate::browser_window::next_protocol_id;
@@ -209,10 +210,54 @@ impl Default for WebviewOptions {
auto_normalize_load_url: Some(true),
use_https_scheme: Some(false),
enable_drag_region_helpers: Some(true),
+ native_file_drop: Some(false),
}
}
}
+fn should_register_native_file_drop(native_file_drop: Option) -> bool {
+ native_file_drop == Some(true)
+}
+
+fn drag_drop_event_payload(event: DragDropEvent) -> Option {
+ let (event_type, paths, position) = match event {
+ DragDropEvent::Enter { paths, position } => (
+ WebviewEventType::DragEnter,
+ Some(
+ paths
+ .into_iter()
+ .map(|path| path.to_string_lossy().into_owned())
+ .collect(),
+ ),
+ Some(position),
+ ),
+ DragDropEvent::Over { position } => (WebviewEventType::DragOver, None, Some(position)),
+ DragDropEvent::Drop { paths, position } => (
+ WebviewEventType::DragDrop,
+ Some(
+ paths
+ .into_iter()
+ .map(|path| path.to_string_lossy().into_owned())
+ .collect(),
+ ),
+ Some(position),
+ ),
+ DragDropEvent::Leave => (WebviewEventType::DragLeave, None, None),
+ // Wry marks this enum non-exhaustive. Unknown future variants are ignored.
+ _ => return None,
+ };
+
+ Some(WebviewEventPayload {
+ event: event_type.name().to_owned(),
+ paths,
+ position: position.map(|(x, y)| WebviewWindowPosition {
+ x: f64::from(x),
+ y: f64::from(y),
+ }),
+ ..Default::default()
+ })
+}
+
#[napi(js_name = "Webview")]
pub struct JsWebview {
// Rc is shared with the owning BrowserWindow so the WebView stays alive
@@ -376,6 +421,19 @@ impl JsWebview {
webview = webview.with_initialization_script(drag_region_script());
}
+ // Install Wry's handler only when explicitly enabled. Returning true consumes the native
+ // drop where supported; Windows uses its replacement WebView2 drop target and ignores this
+ // return value.
+ if should_register_native_file_drop(options.native_file_drop) {
+ let ev_rc = Rc::clone(&event_handler);
+ webview = webview.with_drag_drop_handler(move |event| {
+ if let Some(payload) = drag_drop_event_payload(event) {
+ dispatch_event(&ev_rc, payload);
+ }
+ true
+ });
+ }
+
// ── Navigation handler ────────────────────────────────────────────────────
{
let nav_rc = Rc::clone(&nav_handler);
@@ -1170,3 +1228,79 @@ mod maximize_toggle_tests {
assert_eq!(toggle_maximize_state(true, || false, || true), Some(true));
}
}
+
+#[cfg(test)]
+mod drag_drop_tests {
+ use super::{drag_drop_event_payload, should_register_native_file_drop};
+ use crate::types::WebviewOptions;
+ use std::path::PathBuf;
+ use wry::DragDropEvent;
+
+ #[test]
+ fn native_file_drop_registration_is_opt_in() {
+ assert!(!should_register_native_file_drop(None));
+ assert!(!should_register_native_file_drop(Some(false)));
+ assert!(should_register_native_file_drop(Some(true)));
+ assert_eq!(WebviewOptions::default().native_file_drop, Some(false));
+ }
+
+ #[test]
+ fn drag_enter_preserves_multiple_file_and_directory_paths_and_position() {
+ let payload = drag_drop_event_payload(DragDropEvent::Enter {
+ paths: vec![PathBuf::from("/tmp/one.txt"), PathBuf::from("/tmp/folder")],
+ position: (23, 41),
+ })
+ .expect("known Wry event");
+
+ assert_eq!(payload.event, "drag-enter");
+ assert_eq!(
+ payload.paths,
+ Some(vec!["/tmp/one.txt".to_owned(), "/tmp/folder".to_owned()])
+ );
+ let position = payload.position.expect("drag position");
+ assert_eq!((position.x, position.y), (23.0, 41.0));
+ }
+
+ #[test]
+ fn drag_over_has_only_webview_relative_position() {
+ let payload =
+ drag_drop_event_payload(DragDropEvent::Over { position: (7, 11) }).expect("known Wry event");
+
+ assert_eq!(payload.event, "drag-over");
+ assert_eq!(payload.paths, None);
+ let position = payload.position.expect("drag position");
+ assert_eq!((position.x, position.y), (7.0, 11.0));
+ }
+
+ #[test]
+ fn drag_drop_preserves_all_paths_and_position() {
+ let payload = drag_drop_event_payload(DragDropEvent::Drop {
+ paths: vec![
+ PathBuf::from("/tmp/folder"),
+ PathBuf::from("/tmp/another.txt"),
+ ],
+ position: (101, 202),
+ })
+ .expect("known Wry event");
+
+ assert_eq!(payload.event, "drag-drop");
+ assert_eq!(
+ payload.paths,
+ Some(vec![
+ "/tmp/folder".to_owned(),
+ "/tmp/another.txt".to_owned()
+ ])
+ );
+ let position = payload.position.expect("drop position");
+ assert_eq!((position.x, position.y), (101.0, 202.0));
+ }
+
+ #[test]
+ fn drag_leave_has_no_paths_or_position() {
+ let payload = drag_drop_event_payload(DragDropEvent::Leave).expect("known Wry event");
+
+ assert_eq!(payload.event, "drag-leave");
+ assert_eq!(payload.paths, None);
+ assert!(payload.position.is_none());
+ }
+}