feat(browser): 应用内浏览器插件 + 独立浏览器窗口命令
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m8s

- lib.rs:新增 open_browser_window(label=browser 单窗口复用,原生 navigate 导航,
  只放行 http/https),以及 browser_control(back/forward/reload/close)、
  browser_state(open/url)两个主窗口发起的控制命令。
- 窗口几何按 label 存取:主窗口沿用 window-geom.json,浏览器窗口用 browser-geom.json
  (下限 800x600,换显示器只恢复尺寸)。
- 修 CloseRequested 对非 main 窗口也 prevent_close 的问题:此前浏览器窗口点 ✕ 只是被隐藏,
  页面/音频在后台继续跑且再也关不掉。现在非 main 窗口正常销毁。
- 同步源仓新增 browser 插件(上架白名单 + meta 展示信息 + 产物 plugin-browser.1bcb58.js)。
This commit is contained in:
qiqi committed 2026-11-18 22:40:29 +08:00
1 parent 9891e819b4
commit a4a899f424
7 files changed
+439 -28

No files matched your search

+110 -27
View File
@@ -1,7 +1,7 @@
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::menu::{Menu, MenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewWindow, WindowEvent};
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_fs::FsExt; // 提供 fs_scope():运行时给「资料目录」授权
// 「是否正在真正退出」:托盘菜单的「退出」或 Cmd+Q 才会置位,
@@ -16,15 +16,21 @@ struct WindowGeom {
h: u32,
}
fn geom_file(app: &AppHandle) -> Option<std::path::PathBuf> {
app.path()
.app_config_dir()
.ok()
.map(|d| d.join("window-geom.json"))
fn geom_file(app: &AppHandle, label: &str) -> Option<std::path::PathBuf> {
app.path().app_config_dir().ok().map(|d| {
// 主窗口沿用历史文件名,避免升级后把已记住的位置丢掉一次
if label == "main" {
d.join("window-geom.json")
} else {
d.join(format!("{}-geom.json", label))
}
})
}
// 只在窗口处于普通状态时记录:最大化/全屏时的尺寸不是用户想恢复的那个尺寸
fn save_geom(win: &WebviewWindow) {
// 只在窗口处于普通状态时记录:最大化/全屏时的尺寸不是用户想恢复的那个尺寸。
// 按 label 取窗口,主窗口与浏览器窗口共用同一套机制,各自存各自的文件。
fn save_geom(app: &AppHandle, label: &str) {
let Some(win) = app.get_webview_window(label) else { return };
if win.is_maximized().unwrap_or(false) || win.is_fullscreen().unwrap_or(false) {
return;
}
@@ -32,8 +38,7 @@ fn save_geom(win: &WebviewWindow) {
return;
};
let g = WindowGeom { x: pos.x, y: pos.y, w: size.width, h: size.height };
let app = win.app_handle();
if let Some(p) = geom_file(app) {
if let Some(p) = geom_file(app, label) {
if let Some(dir) = p.parent() {
let _ = std::fs::create_dir_all(dir);
}
@@ -44,14 +49,15 @@ fn save_geom(win: &WebviewWindow) {
}
// 恢复上次窗口大小与位置;中心点不在任何显示器内就只恢复尺寸(换过显示器不至于把窗口丢到屏幕外)
fn restore_geom(win: &WebviewWindow, app: &AppHandle) {
let Some(p) = geom_file(app) else { return };
fn restore_geom(app: &AppHandle, label: &str, min_w: u32, min_h: u32) {
let Some(win) = app.get_webview_window(label) else { return };
let Some(p) = geom_file(app, label) else { return };
let Ok(txt) = std::fs::read_to_string(p) else { return };
let Ok(g) = serde_json::from_str::<WindowGeom>(&txt) else { return };
// 最小尺寸与 tauri.conf.json 的 minWidth/minHeight 对齐:否则会恢复出一个
// 比窗口下限还小的窗口(实测 1051x488 时画布渲染成空白)
let w = g.w.max(1024);
let h = g.h.max(640);
// 最小尺寸与窗口下限对齐:否则会恢复出一个比下限还小的窗口
// (曾实测 1051x488 时画布渲染成空白)
let w = g.w.max(min_w);
let h = g.h.max(min_h);
let _ = win.set_size(PhysicalSize::new(w, h));
let cx = g.x + (w as i32) / 2;
let cy = g.y + (h as i32) / 2;
@@ -348,6 +354,81 @@ fn open_external_url(url: String) -> Result<bool, String> {
Ok(true)
}
// 应用内打开网页:固定 label `browser` 复用同一个窗口,重复打开就聚焦并导航到新地址。
// 加载的是外部网站自己的页面,不受主窗口 CSP 约束(Tauri 的 CSP 只注入自身的 HTML 页面),
// 这也是官方推荐的「加载不可信远程内容」方式,避免 iframe 被对方 X-Frame-Options 拒绝。
// 浏览器窗口不在 capabilities 里 ⇒ 无 IPC 权限,正好不该让它碰到宿主 API。
//
// 保留 async(内部无 await):让命令跑在 Tauri 的异步运行时里,不占 IPC 主线程;
// 建窗/导航都是同步 API,不需要 await 也不需要额外 yield。
#[tauri::command]
async fn open_browser_window(app: AppHandle, url: String) -> Result<bool, String> {
let parsed = url::Url::parse(&url).map_err(|_| "网址格式不合法".to_string())?;
if parsed.scheme() != "http" && parsed.scheme() != "https" {
return Err("只允许 http/https".into());
}
let label = "browser";
// 窗口标题跟着目标站点走,复用窗口时也要更新,否则标题永远是第一次打开的那个站。
let title = parsed
.host_str()
.filter(|h| !h.is_empty())
.unwrap_or("浏览器")
.to_string();
if let Some(win) = app.get_webview_window(label) {
// 已存在:显示、取消最小化、聚焦,再导航到新地址。
let _ = win.show();
let _ = win.unminimize();
let _ = win.set_focus();
let _ = win.set_title(&title);
// 用原生命令导航,不在外部页面的 JS 上下文里执行字符串。
win.navigate(parsed).map_err(|e| e.to_string())?;
return Ok(true);
}
WebviewWindowBuilder::new(&app, label, WebviewUrl::External(parsed))
.title(&title)
.inner_size(1200.0, 820.0)
.min_inner_size(800.0, 600.0)
.center()
.build()
.map_err(|e| e.to_string())?;
// 恢复上次浏览器窗口的位置/大小;没有记录时保持上面的居中默认值。
restore_geom(&app, label, 800, 600);
Ok(true)
}
// 浏览器窗口控制:由主窗口(有 IPC 权限)驱动,browser 窗口自身仍然无 IPC 权限。
// back/forward 用固定字符串且不拼接任何外部输入,不构成注入面。
#[tauri::command]
fn browser_control(app: AppHandle, action: String) -> Result<bool, String> {
let win = app
.get_webview_window("browser")
.ok_or_else(|| "浏览器窗口未打开".to_string())?;
match action.as_str() {
"back" => win.eval("history.back()").map_err(|e| e.to_string())?,
"forward" => win.eval("history.forward()").map_err(|e| e.to_string())?,
"reload" => win.reload().map_err(|e| e.to_string())?,
// 关闭走正常 CloseRequested 路径;主窗口以外不再 prevent_close,会真正销毁。
"close" => win.close().map_err(|e| e.to_string())?,
_ => return Err("未知操作".into()),
}
Ok(true)
}
// 面板用来显示「当前打开的是哪个站」以及窗口是否还活着。
#[tauri::command]
fn browser_state(app: AppHandle) -> Result<serde_json::Value, String> {
match app.get_webview_window("browser") {
Some(win) => Ok(serde_json::json!({
"open": true,
"url": win.url().map(|u| u.to_string()).unwrap_or_default()
})),
None => Ok(serde_json::json!({ "open": false, "url": "" })),
}
}
#[tauri::command]
fn notify_desktop(app: tauri::AppHandle, title: String, body: String) -> Result<bool, String> {
use tauri_plugin_notification::NotificationExt;
@@ -373,7 +454,7 @@ pub fn run() {
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, notify_desktop])
.invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, open_browser_window, browser_control, browser_state, notify_desktop])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
@@ -382,10 +463,8 @@ pub fn run() {
.build(),
)?;
}
// 恢复上次窗口大小/位置
if let Some(win) = app.get_webview_window("main") {
restore_geom(&win, app.handle());
}
// 恢复上次窗口大小/位置(主窗口下限与 tauri.conf 的 minWidth/minHeight 对齐)
restore_geom(app.handle(), "main", 1024, 640);
build_tray(app.handle())?;
// macOS 必须有应用菜单,否则 Cmd+C / Cmd+V / Cmd+X 根本不会进 WebView(Tauri 已知问题)
#[cfg(target_os = "macos")]
@@ -398,10 +477,16 @@ pub fn run() {
// 点关闭按钮 ⇒ 记住窗口尺寸后收进托盘(不退出,后台任务继续)
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let label = window.label();
// 主窗口之外(browser 等)正常关闭:先记几何,再放行销毁。
// 这一步不能省 —— 否则外部网页会「点 ✕ 只是隐藏」,在后台继续跑,
// 用户再也关不掉,只能 Cmd+Q 退整个应用。
if label != "main" {
save_geom(window.app_handle(), label);
return;
}
save_geom(window.app_handle(), "main");
if !QUITTING.load(Ordering::SeqCst) {
if let Some(w) = window.app_handle().get_webview_window("main") {
save_geom(&w);
}
api.prevent_close();
let _ = window.hide();
}
@@ -413,9 +498,7 @@ pub fn run() {
app.run(|app_handle, event| {
// Cmd+Q / 系统退出时也把当前窗口尺寸落盘
if let tauri::RunEvent::ExitRequested { .. } = event {
if let Some(w) = app_handle.get_webview_window("main") {
save_geom(&w);
}
save_geom(app_handle, "main");
}
});
}