How to set a custom Origin for Tauri App? #4912
-
How do I set in the Tauri app a Origin for a window? And it needs to set Origin to connect to an external WebSocket via React. fn main() {
tauri::Builder::default()
.plugin(PluginBuilder::default().build())
.setup(|app| {
#[cfg(debug_assertions)]
app.get_window("main").unwrap().open_devtools();
WindowBuilder::new(app, "main", WindowUrl::App("index.html".into()))
.on_web_resource_request(|req, resp| {
resp.headers_mut().insert(
"Origin",
"https://example.com/".try_into().unwrap(),
);
})
.build()?;
Ok(())
})
.run(tauri::generate_context!())
.expect("failed to run app");
} |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 5 replies
-
Are you asking this because of CORS error? If so, you can turn it off or you can set the allowed ones. |
Beta Was this translation helpful? Give feedback.
-
For Windows something like this could work until we add native support for this let win = app.get_window("main").unwrap();
win.with_webview(|webview| unsafe {
let core = webview.controller().CoreWebView2().unwrap();
let mut _token = EventRegistrationToken::default();
// You'd probably use CONTEXT_WEBSOCKET or whatever fits, see https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2webresourcecontext?view=webview2-dotnet-1.0.1293.44
// Also use a fitting glob filter, so that it doesn't trigger for all requests, see https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2?view=webview2-1.0.1293.44#addwebresourcerequestedfilter
core.AddWebResourceRequestedFilter("*", COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL);
core.add_WebResourceRequested(
WebResourceRequestedEventHandler::create(Box::new(move |webview, args| {
if let Some(args) = args {
let request: ICoreWebView2WebResourceRequest = args.Request().unwrap(); // manual type to make Rust-Analyzer show the types
request
.Headers()
.unwrap()
.SetHeader("Origin", "my-origin")
.unwrap();
}
Ok(())
})),
&mut _token,
);
}); It needs [email protected] and [email protected] crates and i'm not sure how safe all these unwraps are... I'll update this with linux/macos code if i figure out something that works. Edit: 2022-10-25 I found a way to do it on Linux and it's literally the worst thing... Not sure if i will polish my PoC and upload it somewhere at this point as i don't see us supporting/using web extensions at this point anyway 🤔 |
Beta Was this translation helpful? Give feedback.
-
Hello @skorotkiewicz ,
|
Beta Was this translation helpful? Give feedback.
-
This is how I did it on Tauri 2.0.0-rc (Windows only). Please note, I'm not a Rust developer, I merely put together code I found from different repos and used GPT for the rest. So I can't guarantee the safety or reliability of the code. I don't even understand parts of it, specially the lower level code. But it's working for me on Windows and it's the only platform I need. Since this is for a personal project, which I don't plan to distribute anywhere. I wanted to share so experts might correct or improve upon this, or even shame me idk. Packages: windows = "0.58.0"
webview2-com = "0.33.0"
webview2-com-sys = "0.33.0"
Imports: use tauri::Manager;
use webview2_com::WebResourceRequestedEventHandler;
use webview2_com_sys::Microsoft::Web::WebView2::Win32::{
ICoreWebView2WebResourceRequest, COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL,
};
use windows::core::{HSTRING, PCWSTR};
use windows::Win32::System::WinRT::EventRegistrationToken The setup block: .setup(|app| {
let window = app.get_webview_window("main").unwrap();
window
.with_webview(|webview| unsafe {
let core = webview.controller().CoreWebView2().unwrap();
// Create a filter string
let filter = HSTRING::from("*");
// Add a web resource requested filter
core.AddWebResourceRequestedFilter(
PCWSTR(filter.as_wide().as_ptr()), // Convert HSTRING to PCWSTR
COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL,
)
.unwrap();
let mut _token: EventRegistrationToken = EventRegistrationToken::default();
core.add_WebResourceRequested(
&WebResourceRequestedEventHandler::create(Box::new(
move |_webview, args| {
if let Some(args) = args {
let request: ICoreWebView2WebResourceRequest =
args.Request().unwrap();
let mut uri_buffer: windows::core::PWSTR =
windows::core::PWSTR(std::ptr::null_mut());
// Get the URI from the request
request.Uri(&mut uri_buffer).unwrap();
// Calculate the length of the wide string
let length = {
let mut len = 0;
while *uri_buffer.0.add(len) != 0 {
len += 1;
}
len
};
// Create a slice from the PWSTR
let slice =
{ std::slice::from_raw_parts(uri_buffer.0, length) }; // Create a slice from PWSTR
let uri_hstring = windows::core::HSTRING::from_wide(slice);
let uri_str = match uri_hstring {
Ok(hstring) => hstring.to_string_lossy().to_owned(),
Err(_) => String::new(), // Handle the error case, can be customized
};
if !uri_str.starts_with("http://")
&& !uri_str.starts_with("https://")
{
return Ok(()); // Early return if the condition is met
}
if uri_str.starts_with("http://ipc.localhost")
|| uri_str.starts_with("http://localhost:")
{
return Ok(()); // Early return if the condition is met
}
let origin = match uri_str.split_once("://") {
Some((scheme, rest)) => format!(
"{}://{}",
scheme,
rest.split('/').next().unwrap_or("")
),
None => String::new(), // Handle the case where there's no scheme
};
let referer = uri_str.clone(); // Use the full URL for Referer
// Modify the headers
request
.Headers()
.unwrap()
.SetHeader(&HSTRING::from("Origin"), &HSTRING::from(origin)) // Modify the Origin header
.unwrap();
request
.Headers()
.unwrap()
.SetHeader(
&HSTRING::from("Referer"),
&HSTRING::from(referer),
) // Modify the Referer header
.unwrap();
}
Ok(())
},
)),
&mut _token,
)
.unwrap();
// end of with_webview
})
.unwrap();
Ok(())
}) |
Beta Was this translation helpful? Give feedback.
For Windows something like this could work until we add native support for this