Skip to content

Commit

Permalink
Set custom user agent for Tauri app (#352)
Browse files Browse the repository at this point in the history
  • Loading branch information
icidasset committed Aug 27, 2022
1 parent fd4d12d commit d73c03f
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 43 deletions.
51 changes: 11 additions & 40 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 20 additions & 3 deletions src-tauri/Cargo.toml
Expand Up @@ -20,11 +20,28 @@ serde = { version = "^1.0", features = ["derive"] }
tauri = { version = "^1.0.5", features = ["dialog-all", "fs-all", "http-all", "path-all", "shell-open", "shell-open-api", "window-all"] }
tauri-plugin-localhost = { version = "^0.1.0" }
tauri-plugin-window-state = { version = "^0.1.0" }
window-shadows = { version = "^0.2.0" }
window-vibrancy = { version = "^0.1.3" }

[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
webkit2gtk = "0.18.0"

[target.'cfg(target_os = "macos")'.dependencies]
cocoa = "^0.24.0"
objc = "0.2"
objc-foundation = "0.1"
cocoa = "0.24"

[target.'cfg(windows)'.dependencies]
webview2-com = "0.16.0"
windows-implement = "0.37.0"

[target.'cfg(windows)'.dependencies.windows]
version = "0.37.0"
features = [
"Data_Xml_Dom",
"Win32_Foundation",
"Win32_Security",
"Win32_System_Threading",
"Win32_UI_WindowsAndMessaging",
]

[features]
default = [ "custom-protocol" ]
Expand Down
48 changes: 48 additions & 0 deletions src-tauri/src/main.rs
Expand Up @@ -28,6 +28,7 @@ fn main() {
.build()?;

win.set_transparent_titlebar(ToolbarThickness::Thin);
set_user_agent(win);

// Fin
Ok(())
Expand Down Expand Up @@ -89,4 +90,51 @@ unsafe fn make_toolbar(id: cocoa::base::id) {
let new_toolbar = NSToolbar::alloc(id);
new_toolbar.init_();
id.setToolbar_(new_toolbar);
}



// USER AGENT


fn set_user_agent(window: Window) {
let user_agent = "Chrome";

window.with_webview(move |webview| {
#[cfg(windows)]
unsafe {
use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings2;
use windows::core::Interface;

let settings: ICoreWebView2Settings2 = webview
.controller()
.CoreWebView2()
.unwrap()
.Settings()
.unwrap()
.cast()
.unwrap();

settings
.SetUserAgent(user_agent)
.unwrap();
}

#[cfg(target_os = "linux")]
{
use webkit2gtk::{WebViewExt, SettingsExt};
let webview = webview.inner();
let settings = webview.settings().unwrap();
settings.set_user_agent(Some(user_agent));
}

// untested
#[cfg(target_os = "macos")]
unsafe {
use objc::{msg_send, sel, sel_impl};
use objc_foundation::{NSString, INSString};
let agent = NSString::from_str(user_agent);
let () = msg_send![webview.inner(), setCustomUserAgent: agent];
}
});
}

0 comments on commit d73c03f

Please sign in to comment.