tauri icon indicating copy to clipboard operation
tauri copied to clipboard

[bug] Refresh the page WebviewWindow.getByLabel returns inaccurate results.

Open wkl007 opened this issue 3 years ago • 8 comments

Describe the bug

https://user-images.githubusercontent.com/23228335/194795782-346fdf5b-0eba-436c-80a4-4b169b27a304.mp4

Create a window through the new WebviewWindow method, After refreshing the page, the result returned by WebviewWindow.getByLabel is inaccurate.

Reproduction

import { WebviewWindow } from '@tauri-apps/api/window'
import './App.css'

function App () {
  async function createWindow () {
    const existedWindow = WebviewWindow.getByLabel('google-window')
    console.log(existedWindow)
    if (existedWindow) return

    const window = new WebviewWindow('google-window', {
      url: 'https://google.com'
    })

    window.once('tauri://created', () => {
      console.log('window create success')
    })

    window.once('tauri://error', () => {
      console.error('window create failed')
    })
  }

  return (
    <div className="container">
      <h1>Welcome to Tauri!</h1>

      <button style={{ width: '200px', margin: '0 auto' }} onClick={createWindow}>
        create window
      </button>
    </div>
  )
}

export default App

Expected behavior

No response

Platform and versions

$ tauri info

Environment
  › OS: Windows 10.0.22621 X64
  › Webview2: 105.0.1343.53
  › MSVC:
      - Visual Studio Community 2022
      - Visual Studio ���ɹ��� 2022
  › Node.js: 16.17.0
  › npm: 8.15.0
  › pnpm: 7.12.1
  › yarn: 1.22.19
  › rustup: 1.25.1
  › rustc: 1.62.1
  › cargo: 1.62.1
  › Rust toolchain: stable-x86_64-pc-windows-msvc 

Packages
  › @tauri-apps/cli [NPM]: 1.1.1
  › @tauri-apps/api [NPM]: 1.1.0
  › tauri [RUST]: 1.1.1,
  › tauri-build [RUST]: 1.1.1,
  › tao [RUST]: 0.14.0,
  › wry [RUST]: 0.21.1,

App
  › build-type: bundle
  › CSP: unset
  › distDir: ../dist
  › devPath: http://localhost:1420/
  › framework: React

App directory structure
  ├─ .idea
  ├─ .vscode
  ├─ node_modules
  ├─ public
  ├─ src
  └─ src-tauri
Done in 24.53s.

Stack trace

No response

Additional context

No response

wkl007 avatar Oct 10 '22 03:10 wkl007

This is probably related to https://github.com/tauri-apps/tauri/issues/5191 and being fixed in #5456 but using WebviewWindow.getByLabelUnchecked won't validate if it exists or not in the JS cache because sometimes the JS cache is not updated as fast, so we probably need to provide a method that validates it against the cache in rust. so your example would be

const existedWindow = WebviewWindow.getByLabelUnchecked('google-window')
if (await existedWindow.isValid()) return

amrbashir avatar Oct 21 '22 12:10 amrbashir

try this:

// creat a webviewWindow without check
new TauriWindow.WebviewWindow(label, options);
// close it by windowManager and create it again
new TauriWindow.WindowManager(label).close().then(() => {
  new TauriWindow.WebviewWindow(label, options);
});

BTMuli avatar Apr 05 '23 06:04 BTMuli

I have a problem with closing created windows after refresh. I use WebviewWindow.getByLabel to get the window and then try to close it but function doesn't return it - it doesn't exist. Is there solution to this?

Suchyy avatar Aug 07 '23 07:08 Suchyy

Is there solution to this?

Here is what I use now:

#[tauri::command]
async fn create_window(app_handle: tauri::AppHandle, label: String, mut option: WindowConfig) {
  let window_old = app_handle.get_window(&label);
  option.label = label.clone();
  if window_old.is_some() {
    dbg!("window exists");
    window_old.unwrap().close().unwrap();
    return;
  }
  let window_new =
    Some(WindowBuilder::from_config(&app_handle, option).build().expect("failed to create window"));
  window_new.unwrap();
}
export function createTGWindow(
  url: string,
  label: string,
  title: string,
  width: number,
  height: number,
  resizable: boolean,
  visible: boolean = true,
): void {
  // 计算窗口位置
  const left = (window.screen.width - width) / 2;
  const top = (window.screen.height - height) / 2;
  const option: WindowOptions = {
    height,
    width,
    resizable,
    url,
    title,
    visible,
    x: left,
    y: top,
  };
  const isGet = TauriWindow.WebviewWindow.getByLabel(label);
  if (isGet === null) {
    invoke("create_window", { label, option })
      .then(() => {
        createTGWindow(url, label, title, width, height, resizable, visible);
      })
      .catch((err) => {
        console.error(err);
      });
  } else {
    isGet
      .close()
      .then(() => {
        invoke("create_window", { label, option })
          .then(() => {
            console.log(`[createTGWindow][${label}] ${title} created.`);
          })
          .catch((err) => {
            console.error(err);
          });
      })
      .catch((err) => {
        console.error(err);
      });
  }
}

BTMuli avatar Oct 24 '23 06:10 BTMuli

This problem still exist at the 2.0.0 beta version.

name = "tauri" version = "2.0.0-beta.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2bd3d5ccf5316833c0f71c645c25585bddf997a16bea652bf3eab8114273cff"

zhengxiaoyao0716 avatar Mar 05 '24 15:03 zhengxiaoyao0716

is there any fix or hack aroud the issue already

opeolluwa avatar Apr 08 '24 15:04 opeolluwa

The hack is that you create a hidden window on app init through config and then when needed you show it. That way you are not losing its handler.

Suchyy avatar Apr 08 '24 16:04 Suchyy

Thanks mate! I've been fighting it for some time. I'm going to try this out

opeolluwa avatar Apr 08 '24 17:04 opeolluwa