tauri-apps / tauri

Build smaller, faster, and more secure desktop and mobile applications with a web frontend.
https://tauri.app
Apache License 2.0
84.99k stars 2.57k forks source link

[bug] js code was injected multiple times into webview #7454

Open conanchen opened 1 year ago

conanchen commented 1 year ago

Describe the bug

  1. tauri command

[tauri::command]

async fn create_window_finance_yahoo(handle: AppHandle) { let new_window = tauri::WindowBuilder::new( &handle, "finance_yahoo", // the unique window label tauri::WindowUrl::App("https://finance.yahoo.com/".into()), // the url to load ) .build() .unwrap(); }

2. inject js in my plugin
```rust

pub fn plugin_with_options<R: Runtime>(options: Options) -> TauriPlugin<R> {
    let mut plugin_builder = Builder::new("sentry").invoke_handler(generate_handler![
        event,
        breadcrumb,
        create_window_finance_yahoo,
        create_window,
        inject_js_file,
        remove_js_file
    ]);

    if options.javascript.inject {
        println!("plugin_with_options to inject ../dist/inject.min.js");

        plugin_builder = plugin_builder.js_init_script(
            include_str!("../dist/inject.min.js")
                .replace("__DEBUG__", &format!("{}", options.javascript.debug)),
        );
    }

    plugin_builder.build()
}
  1. when the "finance_yahoo" window opened, and check the dev-tool's console:
image

Reproduction

No response

Expected behavior

inject js into webview only once with multiple iframes.

Platform and versions

❯ cargo tauri info

[✔] Environment
    - OS: Mac OS 12.6.0 X64
    ✔ Xcode Command Line Tools: installed
    ✔ rustc: 1.73.0-nightly (1065d876c 2023-07-09)
    ✔ Cargo: 1.73.0-nightly (45782b6b8 2023-07-05)
    ✔ rustup: 1.26.0 (5af9b9484 2023-04-05)
    ✔ Rust toolchain: nightly-x86_64-apple-darwin (environment override by RUSTUP_TOOLCHAIN)
    - node: 16.17.0
    - pnpm: 7.29.1
    - yarn: 1.22.19
    - npm: 8.15.0

[-] Packages
    - tauri [RUST]: 1.4.1
    - tauri-build [RUST]: 1.4.0
    - wry [RUST]: 0.24.3
    - tao [RUST]: 0.16.2
    - @tauri-apps/api [NPM]: 1.4.0
    - @tauri-apps/cli [NPM]: 1.4.0

[-] App
    - build-type: bundle
    - CSP: unset
    - distDir: ../dist
    - devPath: ../dist

Stack trace

No response

Additional context

No response

pewsheen commented 1 year ago

Hmm, only finance.yahoo.com will call the userscript multiple times.

I tried using other sites like google.com and it's fine

pewsheen commented 1 year ago

Currently js_init_script seems to trigger a user-script injection at each subframe (such as loading iframe in the page), so if you only need to call it once, you could probably call eval to run the script once after the window is created.