Thanks to visit codestin.com
Credit goes to lib.rs

#tauri-plugin #js #events #mobile #delegates #intercept #android #ios

sys tauri-plugin-backpressed

Tauri plugin to intercept mobile backpressed events and delegate handling to JS

1 unstable release

0.1.0 Apr 15, 2026

#1514 in GUI

MIT/Apache

46KB
385 lines

tauri-plugin-backpressed

拦截 Tauri Android/iOS 的导航事件(重点是 Android 返回键、iOS back/forward 导航含手势),并把决策交给 JS。

语义约定:

  • handled = true:JS 已处理,本次 native 默认导航被取消。
  • handled = false:JS 不处理,继续 native 默认逻辑。

目录

  • src/lib.rs:Rust 插件入口(注册 Android/iOS 原生插件)
  • android/.../BackpressedPlugin.kt:Android 返回键拦截与回调
  • ios/Sources/BackpressedPlugin.swift:iOS back/forward 导航拦截与回调
  • guest-js/index.ts:JS 侧 API

Rust 侧接入

// src-tauri/src/lib.rs or main.rs
pub fn run() {
  tauri::Builder::default()
    .plugin(tauri_plugin_backpressed::init())
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

JS API

import { onBackpressed } from "tauri-plugin-backpressed";

const unlisten = await onBackpressed(async (event) => {
  // return true  -> JS 处理
  // return false -> native 默认处理
  return false;
});

event:

type BackpressedEvent = {
  requestId: string;
  source: "android_back_button" | "ios_back_forward";
  url?: string;
  canGoBack?: boolean;
};

Vue Router 示例

import { onBackpressed } from "tauri-plugin-backpressed-api";
import { useRouter } from "vue-router";

const router = useRouter();

await onBackpressed async () => {
  if (window.history.length > 1) {
    await router.back();
    return true;
  }
  return false;
});

React Router 示例

import { onBackpressed } from "tauri-plugin-navigate-api";
import { useNavigate } from "react-router-dom";

const navigate = useNavigate();

useEffect(() => {
  let disposed = false;
  onBackpressed(async () => {
    if (window.history.length > 1) {
      navigate(-1);
      return true;
    }
    return false;
  }).then((off) => {
    if (disposed) {
      void off();
    }
  });

  return () => {
    disposed = true;
  };
}, [navigate]);

Web Navigation API 示例

await onBackpressed(async () => {
  if ("navigation" in window && (window as any).navigation?.canGoBack) {
    await (window as any).navigation.back();
    return true;
  }
  return false;
});

说明

  • native 会给每次导航尝试分配 requestId,JS 必须通过 resolve_backpressed 回传 handled
  • 若 JS 超时未回传,native 会自动走默认行为,避免卡死导航。

Dependencies

~17–64MB
~879K SLoC