-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathmod.rs
More file actions
2376 lines (2166 loc) · 75.1 KB
/
mod.rs
File metadata and controls
2376 lines (2166 loc) · 75.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri webview types and functions.
pub(crate) mod plugin;
mod webview_window;
pub use webview_window::{WebviewWindow, WebviewWindowBuilder};
/// Cookie crate used for [`Webview::set_cookie`] and [`Webview::delete_cookie`].
///
/// # Stability
///
/// This re-exported crate is still on an alpha release and might receive updates in minor Tauri releases.
pub use cookie;
use http::HeaderMap;
use serde::Serialize;
use tauri_macros::default_runtime;
pub use tauri_runtime::webview::{NewWindowFeatures, PageLoadEvent, ScrollBarStyle};
// Remove this re-export in v3
pub use tauri_runtime::Cookie;
#[cfg(desktop)]
use tauri_runtime::{
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
WindowDispatch,
};
use tauri_runtime::{
webview::{DetachedWebview, InitializationScript, PendingWebview, WebviewAttributes},
WebviewDispatch,
};
pub use tauri_utils::config::Color;
use tauri_utils::config::{BackgroundThrottlingPolicy, WebviewUrl, WindowConfig};
pub use url::Url;
use crate::{
app::{UriSchemeResponder, WebviewEvent},
event::{EmitArgs, EventTarget},
ipc::{
CallbackFn, CommandArg, CommandItem, CommandScope, GlobalScope, Invoke, InvokeBody,
InvokeError, InvokeMessage, InvokeResolver, Origin, OwnedInvokeResponder, ScopeObject,
},
manager::AppManager,
path::SafePathBuf,
sealed::{ManagerBase, RuntimeOrDispatch},
AppHandle, Emitter, Event, EventId, EventLoopMessage, EventName, Listener, Manager,
ResourceTable, Runtime, Window,
};
use std::{
borrow::Cow,
hash::{Hash, Hasher},
path::{Path, PathBuf},
sync::{Arc, Mutex, MutexGuard},
};
pub(crate) type WebResourceRequestHandler =
dyn Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync;
pub(crate) type NavigationHandler = dyn Fn(&Url) -> bool + Send;
pub(crate) type NewWindowHandler<R> =
dyn Fn(Url, NewWindowFeatures) -> NewWindowResponse<R> + Send + Sync;
pub(crate) type UriSchemeProtocolHandler =
Box<dyn Fn(&str, http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync>;
pub(crate) type OnPageLoad<R> = dyn Fn(Webview<R>, PageLoadPayload<'_>) + Send + Sync + 'static;
pub(crate) type OnDocumentTitleChanged<R> = dyn Fn(Webview<R>, String) + Send + 'static;
pub(crate) type DownloadHandler<R> = dyn Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) type OnWebContentProcessTerminateHandler<R> = dyn Fn(Webview<R>) + Send;
#[derive(Clone, Serialize)]
pub(crate) struct CreatedEvent {
pub(crate) label: String,
}
/// Download event for the [`WebviewBuilder#method.on_download`] hook.
#[non_exhaustive]
pub enum DownloadEvent<'a> {
/// Download requested.
Requested {
/// The url being downloaded.
url: Url,
/// Represents where the file will be downloaded to.
/// Can be used to set the download location by assigning a new path to it.
/// The assigned path _must_ be absolute.
destination: &'a mut PathBuf,
},
/// Download finished.
Finished {
/// The URL of the original download request.
url: Url,
/// Potentially representing the filesystem path the file was downloaded to.
///
/// A value of `None` being passed instead of a `PathBuf` does not necessarily indicate that the download
/// did not succeed, and may instead indicate some other failure - always check the third parameter if you need to
/// know if the download succeeded.
///
/// ## Platform-specific:
///
/// - **macOS**: The second parameter indicating the path the file was saved to is always empty, due to API
/// limitations.
path: Option<PathBuf>,
/// Indicates if the download succeeded or not.
success: bool,
},
}
/// The payload for the [`WebviewBuilder::on_page_load`] hook.
#[derive(Debug, Clone)]
pub struct PageLoadPayload<'a> {
pub(crate) url: &'a Url,
pub(crate) event: PageLoadEvent,
}
impl<'a> PageLoadPayload<'a> {
/// The page URL.
pub fn url(&self) -> &'a Url {
self.url
}
/// The page load event.
pub fn event(&self) -> PageLoadEvent {
self.event
}
}
/// The IPC invoke request.
///
/// # Stability
///
/// This struct is **NOT** part of the public stable API and is only meant to be used
/// by internal code and external testing/fuzzing tools or custom invoke systems.
#[derive(Debug)]
pub struct InvokeRequest {
/// The invoke command.
pub cmd: String,
/// The success callback.
pub callback: CallbackFn,
/// The error callback.
pub error: CallbackFn,
/// URL of the frame that requested this command.
pub url: Url,
/// The body of the request.
pub body: InvokeBody,
/// The request headers.
pub headers: HeaderMap,
/// The invoke key. Must match what was passed to the app manager.
pub invoke_key: String,
}
/// The platform webview handle. Accessed with [`Webview#method.with_webview`];
#[cfg(feature = "wry")]
#[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
pub struct PlatformWebview(tauri_runtime_wry::Webview);
#[cfg(feature = "wry")]
impl PlatformWebview {
/// Returns [`webkit2gtk::WebView`] handle.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[cfg_attr(
docsrs,
doc(cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))
)]
pub fn inner(&self) -> webkit2gtk::WebView {
self.0.clone()
}
/// Returns the WebView2 controller.
#[cfg(windows)]
#[cfg_attr(docsrs, doc(cfg(windows)))]
pub fn controller(
&self,
) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller {
self.0.controller.clone()
}
/// Returns the WebView2 environment.
#[cfg(windows)]
#[cfg_attr(docsrs, doc(cfg(windows)))]
pub fn environment(
&self,
) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Environment {
self.0.environment.clone()
}
/// Returns the [WKWebView] handle.
///
/// [WKWebView]: https://developer.apple.com/documentation/webkit/wkwebview
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
pub fn inner(&self) -> *mut std::ffi::c_void {
self.0.webview
}
/// Returns WKWebView [controller] handle.
///
/// [controller]: https://developer.apple.com/documentation/webkit/wkusercontentcontroller
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
pub fn controller(&self) -> *mut std::ffi::c_void {
self.0.manager
}
/// Returns [NSWindow] associated with the WKWebView webview.
///
/// [NSWindow]: https://developer.apple.com/documentation/appkit/nswindow
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
pub fn ns_window(&self) -> *mut std::ffi::c_void {
self.0.ns_window
}
/// Returns [UIViewController] used by the WKWebView webview NSWindow.
///
/// [UIViewController]: https://developer.apple.com/documentation/uikit/uiviewcontroller
#[cfg(target_os = "ios")]
#[cfg_attr(docsrs, doc(cfg(target_os = "ios")))]
pub fn view_controller(&self) -> *mut std::ffi::c_void {
self.0.view_controller
}
/// Returns handle for JNI execution.
#[cfg(target_os = "android")]
pub fn jni_handle(&self) -> tauri_runtime_wry::wry::JniHandle {
self.0
}
}
/// Response for the new window request handler.
pub enum NewWindowResponse<R: Runtime> {
/// Allow the window to be opened with the default implementation.
Allow,
/// Allow the window to be opened, with the given window.
///
/// ## Platform-specific:
///
/// **Linux**: The webview must be related to the caller webview. See [`WebviewBuilder::related_view`].
/// **Windows**: The webview must use the same environment as the caller webview. See [`WebviewBuilder::environment`].
/// **macOS**: The webview must use the same webview configuration as the caller webview. See [`WebviewBuilder::with_webview_configuration`] and [`NewWindowFeatures::webview_configuration`].
Create {
/// Window that was created.
window: crate::WebviewWindow<R>,
},
/// Deny the window from being opened.
Deny,
}
macro_rules! unstable_struct {
(#[doc = $doc:expr] $($tokens:tt)*) => {
#[cfg(any(test, feature = "unstable"))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
#[doc = $doc]
pub $($tokens)*
#[cfg(not(any(test, feature = "unstable")))]
pub(crate) $($tokens)*
}
}
unstable_struct!(
#[doc = "A builder for a webview."]
struct WebviewBuilder<R: Runtime> {
pub(crate) label: String,
pub(crate) webview_attributes: WebviewAttributes,
pub(crate) web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
pub(crate) navigation_handler: Option<Box<NavigationHandler>>,
pub(crate) new_window_handler: Option<Box<NewWindowHandler<R>>>,
pub(crate) on_page_load_handler: Option<Box<OnPageLoad<R>>>,
pub(crate) document_title_changed_handler: Option<Box<OnDocumentTitleChanged<R>>>,
pub(crate) download_handler: Option<Arc<DownloadHandler<R>>>,
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) on_web_content_process_terminate_handler:
Option<Box<OnWebContentProcessTerminateHandler<R>>>,
}
);
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
impl<R: Runtime> WebviewBuilder<R> {
/// Initializes a webview builder with the given webview label and URL to load.
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating webviews.
///
/// # Examples
///
/// - Create a webview in the setup hook:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
Ok(())
});
```
"####
)]
///
/// - Create a webview in a separate thread:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
tauri::Builder::default()
.setup(|app| {
let handle = app.handle().clone();
std::thread::spawn(move || {
let window = tauri::window::WindowBuilder::new(&handle, "label").build().unwrap();
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
});
Ok(())
});
```
"####
)]
///
/// - Create a webview in a command:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
let window = tauri::window::WindowBuilder::new(&app, "label").build().unwrap();
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::External("https://tauri.app/".parse().unwrap()));
window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
}
```
"####
)]
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn new<L: Into<String>>(label: L, url: WebviewUrl) -> Self {
Self {
label: label.into(),
webview_attributes: WebviewAttributes::new(url),
web_resource_request_handler: None,
navigation_handler: None,
new_window_handler: None,
on_page_load_handler: None,
document_title_changed_handler: None,
download_handler: None,
#[cfg(any(target_os = "macos", target_os = "ios"))]
on_web_content_process_terminate_handler: None,
}
}
/// Initializes a webview builder from a [`WindowConfig`] from tauri.conf.json.
/// Keep in mind that you can't create 2 webviews with the same `label` so make sure
/// that the initial webview was closed or change the label of the new [`WebviewBuilder`].
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
/// You should use `async` commands and separate threads when creating webviews.
///
/// # Examples
///
/// - Create a webview in a command:
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```
#[tauri::command]
async fn create_window(app: tauri::AppHandle) {
let window = tauri::window::WindowBuilder::new(&app, "label").build().unwrap();
let webview_builder = tauri::webview::WebviewBuilder::from_config(&app.config().app.windows.get(0).unwrap().clone());
window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
}
```
"####
)]
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn from_config(config: &WindowConfig) -> Self {
let mut config = config.to_owned();
if let Some(data_directory) = &config.data_directory {
let resolve_data_dir_res = dirs::data_local_dir()
.or({
#[cfg(feature = "tracing")]
tracing::error!("failed to resolve data directory");
None
})
.and_then(|local_dir| {
SafePathBuf::new(data_directory.clone())
.inspect_err(|_err| {
#[cfg(feature = "tracing")]
tracing::error!(
"data_directory `{}` is not a safe path, ignoring config. Validation error was: {_err}",
data_directory.display()
);
})
.map(|p| (local_dir, p))
.ok()
})
.and_then(|(local_dir, data_directory)| {
if data_directory.as_ref().is_relative() {
Some(local_dir.join(&config.label).join(data_directory.as_ref()))
} else {
#[cfg(feature = "tracing")]
tracing::error!(
"data_directory `{}` is not a relative path, ignoring config.",
data_directory.display()
);
None
}
});
if let Some(resolved_data_directory) = resolve_data_dir_res {
config.data_directory = Some(resolved_data_directory);
}
}
Self {
label: config.label.clone(),
webview_attributes: WebviewAttributes::from(&config),
web_resource_request_handler: None,
navigation_handler: None,
new_window_handler: None,
on_page_load_handler: None,
document_title_changed_handler: None,
download_handler: None,
#[cfg(any(target_os = "macos", target_os = "ios"))]
on_web_content_process_terminate_handler: None,
}
}
/// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
///
/// Currently only implemented for the `tauri` URI protocol.
///
/// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
/// but it might be implemented in the future. **Always** check the request URL.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_web_resource_request(|request, response| {
if request.uri().scheme_str() == Some("tauri") {
// if we have a CSP header, Tauri is loading an HTML file
// for this example, let's dynamically change the CSP
if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
// use the tauri helper to parse the CSP policy to a map
let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
// use the tauri helper to get a CSP string from the map
let csp_string = Csp::from(csp_map).to_string();
*csp = HeaderValue::from_str(&csp_string).unwrap();
}
}
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_web_resource_request<
F: Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync + 'static,
>(
mut self,
f: F,
) -> Self {
self.web_resource_request_handler.replace(Box::new(f));
self
}
/// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_navigation(|url| {
// allow the production URL or localhost on dev
url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
self.navigation_handler.replace(Box::new(f));
self
}
/// Set a new window request handler to decide if incoming url is allowed to be opened.
///
/// A new window is requested to be opened by the [window.open] API.
///
/// The closure take the URL to open and the window features object and returns [`NewWindowResponse`] to determine whether the window should open.
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::WebviewBuilder,
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let app_ = app.handle().clone();
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_new_window(move |url, features| {
let builder = tauri::WebviewWindowBuilder::new(
&app_,
// note: add an ID counter or random label generator to support multiple opened windows at the same time
"opened-window",
tauri::WebviewUrl::External("about:blank".parse().unwrap()),
)
.window_features(features)
.on_document_title_changed(|window, title| {
window.set_title(&title).unwrap();
})
.title(url.as_str());
let window = builder.build().unwrap();
tauri::webview::NewWindowResponse::Create { window }
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
///
/// # Platform-specific
///
/// - **Android / iOS**: Not supported.
/// - **Windows**: The closure is executed on a separate thread to prevent a deadlock.
///
/// [window.open]: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
pub fn on_new_window<
F: Fn(Url, NewWindowFeatures) -> NewWindowResponse<R> + Send + Sync + 'static,
>(
mut self,
f: F,
) -> Self {
self.new_window_handler.replace(Box::new(f));
self
}
/// Defines a closure to be executed when document title change.
pub fn on_document_title_changed<F: Fn(Webview<R>, String) + Send + 'static>(
mut self,
f: F,
) -> Self {
self.document_title_changed_handler.replace(Box::new(f));
self
}
/// Set a download event handler to be notified when a download is requested or finished.
///
/// Returning `false` prevents the download from happening on a [`DownloadEvent::Requested`] event.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::{DownloadEvent, WebviewBuilder},
};
tauri::Builder::default()
.setup(|app| {
let window = WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_download(|webview, event| {
match event {
DownloadEvent::Requested { url, destination } => {
println!("downloading {}", url);
*destination = "/home/tauri/target/path".into();
}
DownloadEvent::Finished { url, path, success } => {
println!("downloaded {} to {:?}, success: {}", url, path, success);
}
_ => (),
}
// let the download start
true
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.download_handler.replace(Arc::new(f));
self
}
/// Defines a closure to be executed when a page load event is triggered.
/// The event can be either [`PageLoadEvent::Started`] if the page has started loading
/// or [`PageLoadEvent::Finished`] when the page finishes loading.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust,no_run
use tauri::{
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
window::WindowBuilder,
webview::{PageLoadEvent, WebviewBuilder},
};
use http::header::HeaderValue;
use std::collections::HashMap;
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
.on_page_load(|webview, payload| {
match payload.event() {
PageLoadEvent::Started => {
println!("{} finished loading", payload.url());
}
PageLoadEvent::Finished => {
println!("{} finished loading", payload.url());
}
}
});
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
```
"####
)]
pub fn on_page_load<F: Fn(Webview<R>, PageLoadPayload<'_>) + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.on_page_load_handler.replace(Box::new(f));
self
}
/// Defines a closure to be executed when the web content process terminates.
///
/// ## Platform-specific
///
/// - **Linux / Windows / Android:** Unsupported.
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn on_web_content_process_terminate<F: Fn(Webview<R>) + Send + 'static>(
mut self,
f: F,
) -> Self {
self
.on_web_content_process_terminate_handler
.replace(Box::new(f));
self
}
pub(crate) fn into_pending_webview<M: Manager<R>>(
mut self,
manager: &M,
window_label: &str,
) -> crate::Result<PendingWebview<EventLoopMessage, R>> {
let mut pending = PendingWebview::new(self.webview_attributes, self.label.clone())?;
pending.navigation_handler = self.navigation_handler.take();
pending.new_window_handler = self.new_window_handler.take().map(|handler| {
Box::new(
move |url, features: NewWindowFeatures| match handler(url, features) {
NewWindowResponse::Allow => tauri_runtime::webview::NewWindowResponse::Allow,
#[cfg(mobile)]
NewWindowResponse::Create { window: _ } => {
tauri_runtime::webview::NewWindowResponse::Allow
}
#[cfg(desktop)]
NewWindowResponse::Create { window } => {
tauri_runtime::webview::NewWindowResponse::Create {
window_id: window.window.window.id,
}
}
NewWindowResponse::Deny => tauri_runtime::webview::NewWindowResponse::Deny,
},
)
as Box<
dyn Fn(Url, NewWindowFeatures) -> tauri_runtime::webview::NewWindowResponse
+ Send
+ Sync
+ 'static,
>
});
if let Some(document_title_changed_handler) = self.document_title_changed_handler.take() {
let label = pending.label.clone();
let manager = manager.manager_owned();
pending
.document_title_changed_handler
.replace(Box::new(move |title| {
if let Some(w) = manager.get_webview(&label) {
document_title_changed_handler(w, title);
}
}));
}
pending.web_resource_request_handler = self.web_resource_request_handler.take();
if let Some(download_handler) = self.download_handler.take() {
let label = pending.label.clone();
let manager = manager.manager_owned();
pending.download_handler.replace(Arc::new(move |event| {
if let Some(w) = manager.get_webview(&label) {
download_handler(
w,
match event {
tauri_runtime::webview::DownloadEvent::Requested { url, destination } => {
DownloadEvent::Requested { url, destination }
}
tauri_runtime::webview::DownloadEvent::Finished { url, path, success } => {
DownloadEvent::Finished { url, path, success }
}
},
)
} else {
false
}
}));
}
let label_ = pending.label.clone();
let manager_ = manager.manager_owned();
pending
.on_page_load_handler
.replace(Box::new(move |url, event| {
if let Some(w) = manager_.get_webview(&label_) {
if let Some(handler) = self.on_page_load_handler.as_ref() {
handler(w, PageLoadPayload { url: &url, event });
}
}
}));
#[cfg(any(target_os = "macos", target_os = "ios"))]
if let Some(on_web_content_process_terminate_handler) =
self.on_web_content_process_terminate_handler.take()
{
let label = pending.label.clone();
let manager = manager.manager_owned();
pending
.on_web_content_process_terminate_handler
.replace(Box::new(move || {
if let Some(w) = manager.get_webview(&label) {
on_web_content_process_terminate_handler(w);
}
}));
}
manager
.manager()
.webview
.prepare_webview(manager, pending, window_label)
}
/// Creates a new webview on the given window.
#[cfg(desktop)]
pub(crate) fn build(
self,
window: Window<R>,
position: Position,
size: Size,
) -> crate::Result<Webview<R>> {
let app_manager = window.manager();
let mut pending = self.into_pending_webview(&window, window.label())?;
pending.webview_attributes.bounds = Some(tauri_runtime::dpi::Rect { size, position });
let use_https_scheme = pending.webview_attributes.use_https_scheme;
let webview = match &mut window.runtime() {
RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_webview(pending),
_ => unimplemented!(),
}
.map(|webview| {
app_manager
.webview
.attach_webview(window.clone(), webview, use_https_scheme)
})?;
Ok(webview)
}
}
/// Webview attributes.
impl<R: Runtime> WebviewBuilder<R> {
/// Sets whether clicking an inactive window also clicks through to the webview.
#[must_use]
pub fn accept_first_mouse(mut self, accept: bool) -> Self {
self.webview_attributes.accept_first_mouse = accept;
self
}
/// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// Since it runs on all top-level document navigations,
/// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
///
/// This is executed only on the main frame.
/// If you only want to run it in all frames, use [`Self::initialization_script_for_all_frames`] instead.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust
use tauri::{WindowBuilder, Runtime};
const INIT_SCRIPT: &str = r#"
if (window.location.origin === 'https://tauri.app') {
console.log("hello world from js init script");
window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
}
"#;
fn main() {
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()))
.initialization_script(INIT_SCRIPT);
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
}
```
"####
)]
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
#[must_use]
pub fn initialization_script(mut self, script: impl Into<String>) -> Self {
self
.webview_attributes
.initialization_scripts
.push(InitializationScript {
script: script.into(),
for_main_frame_only: true,
});
self
}
/// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// Since it runs on all top-level document navigations and also child frame page navigations,
/// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
///
/// This is executed on all frames (main frame and also sub frames).
/// If you only want to run the script in the main frame, use [`Self::initialization_script`] instead.
///
/// ## Platform-specific
///
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// # Examples
///
#[cfg_attr(
feature = "unstable",
doc = r####"
```rust
use tauri::{WindowBuilder, Runtime};
const INIT_SCRIPT: &str = r#"
if (window.location.origin === 'https://tauri.app') {
console.log("hello world from js init script");
window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
}
"#;
fn main() {
tauri::Builder::default()
.setup(|app| {
let window = tauri::window::WindowBuilder::new(app, "label").build()?;
let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()))
.initialization_script_for_all_frames(INIT_SCRIPT);
let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
Ok(())
});
}
```
"####
)]
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
#[must_use]
pub fn initialization_script_for_all_frames(mut self, script: impl Into<String>) -> Self {
self
.webview_attributes
.initialization_scripts
.push(InitializationScript {
script: script.into(),
for_main_frame_only: false,
});
self
}
/// Set the user agent for the webview
#[must_use]
pub fn user_agent(mut self, user_agent: &str) -> Self {
self.webview_attributes.user_agent = Some(user_agent.to_string());
self
}
/// Set additional arguments for the webview.
///
/// ## Platform-specific
///
/// - **macOS / Linux / Android / iOS**: Unsupported.
///
/// ## Warning
///
/// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
/// so if you use this method, you also need to disable these components by yourself if you want.
#[must_use]