Handling a cross-click to close an app on Pywebview

1 week ago 8
ARTICLE AD BOX

I recently ran into a problem: I needed to create a pywebview app, but I wanted to customize the top control bar where the buttons for minimizing and closing the app are located. First, to make sure it worked, I implemented it without hiding the top bar using arguments in window.start(). I created the following HTML file:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="global.css"> <link rel="stylesheet" href="normalize.css"> <link rel="stylesheet" href="header.css"> </head> <body> <header class="top_frame"> <svg class="collapse_button" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://w3.org"> <path d="M19 13H5V11H19V13Z" fill="currentColor"/> </svg> <a><svg class="open_in_full_screen_button" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path> </svg></a> <div class="close_button__wrapper"> <svg class="close_button" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://w3.org"> <line x1="18" y1="6" x2="6" y2="18"></line> <line x1="6" y1="6" x2="18" y2="18"></line> </svg> </div> </header> <script src="js/header.js"></script> </body> </html>

I recently ran into a problem: I needed to create a WebView app, but I wanted to customize the top control bar where the buttons for minimizing and closing the app are located. First, to make sure it worked, I implemented it without hiding the top bar using arguments in windows.start(). I created the following HTML file:

Then I created a JS file to handle cross-clicks, but it didn't work.

const close_button = document.querySelector(".close_button"); close_button.onclick = function () { pywebview.api.close_window() }

Next, I wrote an implementation for the close_window() function in a separate .py file, which I imported into the main file from which I launched the window.

import sys import webview class ui_header_api_handler(): def minimize_window(self): webview.windows[0].minimize() def close_window(self): # TODO: добавить сбда в последующем логику сохранения и т.д sys.exit(0)

main.py

import webview from ui_api import ui_header_api_handler ui_header_api_handler = ui_header_api_handler.ui_header_api_handler() webview.create_window("Main Window", "index.html", js_api=ui_header_api_handler) webview.start(debug=True)

If anyone knows what the problem is with my program, please let me know.

Thanks in advance!

Read Entire Article