0%
基于 Tarui 的 JsBridge
rust
use tauri::command;
use std::fmt::format;
use std::process::Command;
use std::env;
#[command]
fn run_js_script(name: &str, args: &str) -> String {
let current_dir = env::current_dir().expect("Unable to get current directory");
let js_file_path = current_dir.join(format!("jsBridge/{name}"));
let output = Command::new("node")
.arg(js_file_path)
.arg(args)
.output()
.expect("Failed to execute command");
if !output.status.success() {
let error_message = String::from_utf8_lossy(&output.stderr);
println!("Error running script: {}", error_message);
return "Error".to_string(); // To indicate error in JS execution
}
// Convert the output to a string and trim whitespace
let res = String::from_utf8_lossy(&output.stdout).trim().to_string();
println!("{res}");
return res;
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![run_js_script])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
js
console.log('Hello Tauri')
js
import { invoke } from '@tauri-apps/api'
invoke('run_js_script', {name: 'main.js', args: '-name:123'})
.then((response) => console.log(JSON.parse(response)))
.catch(e => console.error(2, e))
太狠了我真是。