### Hello World with pywebview
Source: https://pywebview.flowrl.com/guide
Create a basic window with a title and URL, then start the pywebview application. This is a simple way to get started with pywebview.
```python
import webview
webview.create_window('Hello world', 'https://pywebview.flowrl.com/')
webview.start()
```
--------------------------------
### Install pywebview with QT5 dependencies
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with QT5 dependencies. This is an alternative to the default QT installation.
```bash
pip install pywebview[qt5]
```
--------------------------------
### Create and Start a Basic Window
Source: https://pywebview.flowrl.com/guide/usage.html
This is the minimum code required to create a window and start the pywebview GUI loop.
```python
import webview
window = webview.create_window('Woah dude!', 'https://pywebview.flowrl.com')
webview.start()
```
--------------------------------
### Install pywebview with PySide6 dependencies
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with PySide6 dependencies. This is an alternative QT binding.
```bash
pip install pywebview[pyside6]
```
--------------------------------
### Install pywebview
Source: https://pywebview.flowrl.com/guide
Install the pywebview library using pip. Additional libraries may be required on some Linux platforms.
```bash
pip install pywebview
```
--------------------------------
### Install pywebview with QT dependencies on Linux
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with QT dependencies, primarily for Linux users. This command installs PyQT6.
```bash
pip install pywebview[qt]
```
--------------------------------
### Install pywebview with PySide2 dependencies
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with PySide2 dependencies. This is an alternative QT binding.
```bash
pip install pywebview[pyside2]
```
--------------------------------
### Force QT Renderer on Linux via webview.start()
Source: https://pywebview.flowrl.com/guide/web_engine.html
Use this to force the QT renderer programmatically on Linux systems when starting the webview application.
```python
import webview
webview.start(gui='qt')
```
--------------------------------
### Install QtWebKit dependencies on Debian-based systems
Source: https://pywebview.flowrl.com/guide/installation.html
Installs QtWebKit dependencies on Debian-based systems using apt. This is a legacy option but available on more platforms.
```bash
sudo apt install python3-pyqt5 python3-pyqt5.qtwebkit python-pyqt5 python-pyqt5.qtwebkit libqt5webkit5-dev
```
--------------------------------
### Install QTWebChannel dependencies on Debian-based systems
Source: https://pywebview.flowrl.com/guide/installation.html
Installs QTWebChannel dependencies on Debian-based systems using apt. This is the more modern and preferred method for QT on Linux.
```bash
sudo apt install python3-pyqt5 python3-pyqt5.qtwebengine python3-pyqt5.qtwebchannel libqt5webkit5-dev
```
--------------------------------
### Install pywebview with CEF support
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with CEF (Chromium Embedded Framework) support. CEF is only available for Windows.
```bash
pip install pywebview[cef]
```
--------------------------------
### Install Python 3 with Homebrew and Create Virtual Environment
Source: https://pywebview.flowrl.com/guide/faq.html
Use this command to install Python 3 via Homebrew and create a virtual environment for pywebview to avoid macOS terminal key event issues.
```bash
brew install python3
virtualenv pywebview_env -p python3
```
--------------------------------
### Install pywebview with SSL support
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with SSL support, including the 'cryptography' package. This is needed for using HTTPS in a local HTTP server.
```bash
pip install pywebview[ssl]
```
--------------------------------
### Start HTTP server with SSL
Source: https://pywebview.flowrl.com/guide/usage.html
Enable SSL for the internal Bottle.py HTTP server by setting `ssl=True` in `webview.start()`. This is used for serving static files from the entrypoint directory.
```python
import webview
webview.create_window('Woah dude!', 'src/index.html')
webview.start(ssl=True)
```
--------------------------------
### Install pywebview with Android support
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with support for Android development. Refer to Kivy's packaging instructions for Android.
```bash
pip install pywebview[android]
```
--------------------------------
### Set CEF Renderer via webview.start()
Source: https://pywebview.flowrl.com/guide/web_engine.html
Use this to set the CEF renderer programmatically when starting the webview application.
```python
import webview
webview.start(gui='cef')
```
--------------------------------
### Install PyGObject dependencies for GTK on Ubuntu
Source: https://pywebview.flowrl.com/guide/installation.html
Installs PyGObject and GTK dependencies on Ubuntu for use with pywebview's GTK backend. Ensure WebKit2 version 2.22 or greater is installed.
```bash
sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0 gir1.2-webkit2-4.1
```
--------------------------------
### Install core PyObjC packages for macOS
Source: https://pywebview.flowrl.com/guide/installation.html
Installs the necessary PyObjC packages for pywebview on macOS. These are often pre-installed with Python on macOS, but may need separate installation for standalone Python.
```bash
pyobjc-core
pyobjc-framework-Cocoa
pyobjc-framework-Quartz
pyobjc-framework-WebKit
pyobjc-framework-security
```
--------------------------------
### Install pywebview with GTK dependencies on Linux
Source: https://pywebview.flowrl.com/guide/installation.html
Installs pywebview with GTK dependencies, specifically for Linux users who prefer GTK over QT. Ensure GTK is available on your system.
```bash
pip install pywebview[gtk]
```
--------------------------------
### Create Window with Local Flask Server
Source: https://pywebview.flowrl.com/guide/architecture.html
Integrate a local Flask web server with pywebview. The Flask app instance is passed directly to create_window. Ensure Flask is installed.
```python
server = Flask(__name__, static_folder='.', template_folder='.')
webview.create_window('My first pywebview application', server)
webview.start()
```
--------------------------------
### Shared State Example
Source: https://pywebview.flowrl.com/guide/interdomain.html
Demonstrates how to share data between Python and Javascript using the `Window.state` and `pywebview.state` objects. Changes on top-level properties are propagated bidirectionally. Binary data can be passed via Base64 encoding.
```python
import webview
window = webview.create_window('Shared State', 'index.html')
window.state.hello = 'world' # Propagates to pywebview.state.hello in JS
webview.start(debug=True)
```
--------------------------------
### Enable JavaScript Debugging
Source: https://pywebview.flowrl.com/guide/debugging.html
Set `debug=True` when starting the webview window to enable the web inspector for JavaScript. This works on macOS, GTK, and QT (QTWebEngine only).
```python
import webview
webview.create_window('Woah dude!', 'https://pywebview.flowrl.com/hello')
webview.start(debug=True)
```
--------------------------------
### Enable pywebview Debug Logging
Source: https://pywebview.flowrl.com/guide/debugging.html
To enable debug logging for the pywebview library itself, set the `PYWEBVIEW_LOG` environment variable to `debug` before starting your application.
```bash
export PYWEBVIEW_LOG=debug
```
--------------------------------
### Get pywebview Android Jar Path
Source: https://pywebview.flowrl.com/guide/freezing.html
Use this Python code to find the full path to the `pywebview-android.jar` file, which is needed for Android builds.
```python
from webview import util
print(util.android_jar_path())
```
--------------------------------
### Get Elements
Source: https://pywebview.flowrl.com/guide/dom.html
Retrieves DOM elements from the webview using CSS selectors. It can return a single element or a list of elements.
```APIDOC
## Get Elements
Retrieves DOM elements based on CSS selectors.
### Parameters
- **selector** (string) - The CSS selector to match elements.
### Returns
- `Element` or `None`: If `get_element` is used, returns the first matching element or `None` if no match is found.
- `list[Element]`: If `get_elements` is used, returns a list of all matching elements.
### Example
```python
element = window.dom.get_element('#element-id')
elements = window.dom.get_elements('div')
```
```
--------------------------------
### Get DOM Elements
Source: https://pywebview.flowrl.com/guide/dom.html
Retrieve single or multiple DOM elements using CSS selectors. `get_element` returns the first match or `None`, while `get_elements` returns a list of all matches.
```python
element = window.dom.get_element('#element-id') # returns a first matching Element or None
elements = window.dom.get_elements('div') # returns a list of matching Elements
```
--------------------------------
### Manage Multiple Windows and Events
Source: https://pywebview.flowrl.com/guide/usage.html
Demonstrates creating multiple windows and attaching an event handler to a window's 'shown' event to access window information.
```python
import webview
def handler():
print(f'There are {len(webview.windows)} windows')
print(f'Active window: {webview.active_window().title}')
first_window = webview.create_window('pywebview docs', 'https://pywebview.flowrl.com')
second_window = webview.create_window('Woah dude!', 'https://woot.fi')
second_window.events.shown += handler
webview.start()
```
--------------------------------
### Execute Backend Logic in a Separate Thread
Source: https://pywebview.flowrl.com/guide/usage.html
Shows how to run custom backend logic concurrently with the GUI by passing a function to webview.start(). This allows for operations like toggling fullscreen or evaluating JavaScript in the window.
```python
import webview
def custom_logic(window):
window.toggle_fullscreen()
window.evaluate_js('alert("Nice one brother")')
window = webview.create_window('Woah dude!', html='
Woah dude!
')
webview.start(custom_logic, window)
# anything below this line will be executed after program is finished executing
pass
```
--------------------------------
### Serve files using file:// protocol
Source: https://pywebview.flowrl.com/guide/usage.html
Serve files directly using the `file://` protocol with an absolute path. This method is not recommended for distribution due to potential limitations and handling issues by web renderers.
```python
import webview
# this will be served as file:///home/pywebview/project/index.html
webview.create_window('Woah dude!', '/home/pywebview/project/index.html')
webview.start()
```
--------------------------------
### Force QT Renderer on Linux via Environment Variable
Source: https://pywebview.flowrl.com/guide/web_engine.html
Use this to force the QT renderer on Linux systems via the environment variable.
```bash
export PYWEBVIEW_GUI=qt
```
--------------------------------
### Integrate External WSGI Server (Flask)
Source: https://pywebview.flowrl.com/guide/usage.html
Serve content using an external WSGI-compatible HTTP server like Flask. Pass the server application object as the URL to `webview.create_window()`.
```python
from flask import Flask
import webview
server = Flask(__name__, static_folder='./assets', template_folder='./templates')
@server.route("/")
def hello_world():
return "Hello, World!"
if __name__ == '__main__':
webview.create_window('Flask example', server)
webview.start()
```
--------------------------------
### Create Window with External URL
Source: https://pywebview.flowrl.com/guide/architecture.html
Use this to open a window pointing to a remote or local web server URL. Ensure the web server is running.
```python
webview.create_window('Simple browser', 'https://pywebview.flowrl.com')
webview.start()
```
--------------------------------
### Window Object Methods
Source: https://pywebview.flowrl.com/guide/usage.html
Provides a list of commonly used methods for interacting with the browser window, such as loading URLs, executing JavaScript, and managing window state.
```APIDOC
## Window Object Methods
### Description
Provides a list of commonly used methods for interacting with the browser window, such as loading URLs, executing JavaScript, and managing window state.
### Methods
- **`window.load_url(url)`**
- Description: Loads a new URL in the window.
- Parameters:
- `url` (string) - Required - The URL to load.
- **`window.load_html(content)`**
- Description: Loads HTML content directly into the window.
- Parameters:
- `content` (string) - Required - The HTML content to load.
- **`window.evaluate_js(script)`**
- Description: Executes JavaScript code in the window and returns the result.
- Parameters:
- `script` (string) - Required - The JavaScript code to execute.
- Returns: The result of the JavaScript execution.
- **`window.toggle_fullscreen()`**
- Description: Toggles the window between fullscreen and windowed mode.
- **`window.resize(width, height)`**
- Description: Resizes the window to the specified width and height.
- Parameters:
- `width` (integer) - Required - The desired width of the window.
- `height` (integer) - Required - The desired height of the window.
- **`window.move(x, y)`**
- Description: Moves the window to the specified x and y coordinates.
- Parameters:
- `x` (integer) - Required - The desired x-coordinate for the window.
- `y` (integer) - Required - The desired y-coordinate for the window.
- **`window.hide()`**
- Description: Hides the window.
- **`window.show()`**
- Description: Shows the window if it is hidden.
- **`window.minimize()`**
- Description: Minimizes the window.
- **`window.restore()`**
- Description: Restores the window if it is minimized or maximized.
- **`window.destroy()`**
- Description: Closes the window.
```
--------------------------------
### Pyinstaller One-File Build
Source: https://pywebview.flowrl.com/guide/freezing.html
Use the `--onefile` flag with pyinstaller to create a single executable file. This command also includes `index.html` as data.
```bash
pyinstaller main.py --add-data index.html:. --onefile
```
--------------------------------
### Subscribe to Window Closing Event
Source: https://pywebview.flowrl.com/guide/usage.html
Demonstrates how to subscribe to the 'closing' event of a pywebview window to execute a function before the window is closed. Requires the webview library.
```python
import webview
def on_closing():
print("Window is about to close")
window = webview.create_window('Woah dude!', 'https://pywebview.flowrl.com')
window.events.closing += on_closing
webview.start()
```
--------------------------------
### Window Events
Source: https://pywebview.flowrl.com/guide/usage.html
Details the available events for the Window object, including how to subscribe and unsubscribe from them.
```APIDOC
## Window Events
### Description
Window object has these window manipulation and navigation events: `closed`, `closing`, `loaded`, `before_load`, `before_show`, `shown`, `minimized`, `maximized`, `restored`, `resized`, `moved`. Window events can be found under the `window.events` container.
### Usage
To subscribe to an event use the `+=` operator and `-=` for unsubscribing.
### Example
```python
import webview
def on_closing():
print("Window is about to close")
window = webview.create_window('Woah dude!', 'https://pywebview.flowrl.com')
window.events.closing += on_closing
webview.start()
```
### Available Events
- `closed`
- `closing`
- `loaded`
- `before_load`
- `before_show`
- `shown`
- `minimized`
- `maximized`
- `restored`
- `resized`
- `moved`
```
--------------------------------
### Pyinstaller One-File with JavaScript Build Directory
Source: https://pywebview.flowrl.com/guide/freezing.html
Creates a single executable file for an application that uses a pre-built JavaScript project directory. This is useful for bundling frontend assets.
```bash
pyinstaller main.py --add-data output:. --onefile
```
--------------------------------
### Pyinstaller with JavaScript Build Directory
Source: https://pywebview.flowrl.com/guide/freezing.html
When using JavaScript frameworks like Vue or React, package the built project directory using pyinstaller's `--add-data` option. Ensure the build directory name does not conflict with pyinstaller's default.
```bash
pyinstaller main.py --add-data output:.
```
--------------------------------
### Set CEF Renderer via Environment Variable
Source: https://pywebview.flowrl.com/guide/web_engine.html
Use this to set the CEF renderer as the default for pywebview on Windows via the environment variable.
```bash
export PYWEBVIEW_GUI=cef
```
--------------------------------
### Execute Javascript from Python (unsafe-eval)
Source: https://pywebview.flowrl.com/guide/interdomain.html
Shows how to execute Javascript code directly using `window.run_js` without any wrapper. This method does not return a result or handle exceptions and is useful when `unsafe-eval` CSP is required.
```python
import webview
window = webview.create_window('Run JS Unsafe', 'index.html')
window.run_js("alert('This is an unsafe eval!');")
webview.start()
```
--------------------------------
### Basic Pyinstaller Command
Source: https://pywebview.flowrl.com/guide/freezing.html
A basic pyinstaller command to package a Python application that uses `index.html` as its content. The `.` specifies the current directory for the data file.
```bash
pyinstaller main.py --add-data index.html:.
```
--------------------------------
### Expose Python Functions to Javascript at Runtime
Source: https://pywebview.flowrl.com/guide/interdomain.html
Demonstrates exposing Python functions to Javascript using `window.expose()`. Exposed functions are available as `pywebview.api.func_name` and can be exposed at runtime. These functions execute in separate threads and return promises.
```python
import webview
def multiply(a, b):
return a * b
window = webview.create_window('Expose Function', 'index.html')
window.expose(multiply)
webview.start()
```
--------------------------------
### Execute Javascript from Python (synchronous)
Source: https://pywebview.flowrl.com/guide/interdomain.html
Demonstrates synchronous execution of Javascript code from Python using `window.evaluate_js` without a callback. The return value of the Javascript code is returned directly.
```python
import webview
window = webview.create_window('Evaluate JS Sync', 'index.html')
result = window.evaluate_js("10 * 10")
print(f'JS result: {result}')
webview.start()
```
--------------------------------
### Buildozer Spec for pywebview on Android
Source: https://pywebview.flowrl.com/guide/freezing.html
Include these lines in your `buildozer.spec` file to bundle pywebview correctly for Android builds.
```ini
requirements = python3,kivy,pywebview
android.add_jars =
```
--------------------------------
### Subscribe to State Changes
Source: https://pywebview.flowrl.com/guide/interdomain.html
Shows how to subscribe to state change events in Javascript. The callback receives the event type, key, and value of the changed property.
```javascript
pywebview.state += (event_type, key, value) => {
console.log(`Event: ${event_type}, Key: ${key}, Value: ${value}`);
}
```
--------------------------------
### Enable Remote Debugging with a Port
Source: https://pywebview.flowrl.com/guide/debugging.html
For remote debugging with `edgechromium` and `qt` renderers, set `webview.settings['REMOTE_DEBUGGING_PORT']` to your desired port number.
```python
webview.settings['REMOTE_DEBUGGING_PORT'] = 8080 # Example port
```
--------------------------------
### Execute Javascript from Python (with callback)
Source: https://pywebview.flowrl.com/guide/interdomain.html
Illustrates executing Javascript code from Python using `window.evaluate_js`. A callback function can be provided to handle the Javascript result, which is converted to Python types. Errors are rethrown as `JavascriptException`.
```python
import webview
def js_callback(result):
print(f'JS callback received: {result}')
window = webview.create_window('Evaluate JS', 'index.html')
window.evaluate_js("document.title = 'New Title'; return 1 + 2;", js_callback)
webview.start()
```
--------------------------------
### Create Element
Source: https://pywebview.flowrl.com/guide/dom.html
Creates a new DOM element and inserts it into the webview. The insertion mode can be controlled using `ManipulationMode`.
```APIDOC
## Create Element
Creates a new DOM element. The `mode` parameter controls where the new element is inserted relative to its parent.
### Parameters
- **html** (string) - The HTML string to create the element from.
- **parent** (string, optional) - A CSS selector for the parent element. Defaults to the document body.
- **mode** (ManipulationMode, optional) - The insertion mode. Defaults to `ManipulationMode.LastChild`.
### `ManipulationMode` Options
- `LastChild`: Insert as the last child of the parent.
- `FirstChild`: Insert as the first child of the parent.
- `Before`: Insert before the parent element.
- `After`: Insert after the parent element.
- `Replace`: Replace the parent element with the new element.
### Example
```python
element = window.dom.create_element('
new element
')
element = window.dom.create_element('
Warning
', parent='#container', mode=ManipulationMode.FirstChild)
```
```
--------------------------------
### Create DOM Elements
Source: https://pywebview.flowrl.com/guide/dom.html
Use `create_element` to insert new HTML elements into the DOM. Specify the parent element and manipulation mode for precise placement.
```python
element = window.dom.create_element('
new element
') # insert a new element as body's last child
element = window.dom.create_element('
Warning
' parent='#container', mode=ManipulationMode.FirstChild) # insert a new element to #containaer as a first child
```
--------------------------------
### Control Element Visibility and Focus
Source: https://pywebview.flowrl.com/guide/dom.html
Manage element visibility with `hide()`, `show()`, and `toggle()`. Use `focus()` and `blur()` to control element focus, and check `visible` and `focused` properties.
```python
element.hide() # hide element
print(element.visible) # False
element.show() # show element
print(element.visible) # True
element.toggle() # toggle visibility
element.focus() # focus element
print(element.focused) # True if element can be focused
element.blur() # blur element
print(element.focused) # False
```
--------------------------------
### Event Subscription
Source: https://pywebview.flowrl.com/guide/dom.html
Allows subscribing to and unsubscribing from DOM events directly from Python code. Supports custom event handlers with advanced options.
```APIDOC
## Events
Subscribes to and unsubscribes from DOM events.
### Event Subscription
- **element.on(event_name, handler)**: Subscribes a handler function to a specific event.
- **element.off(event_name, handler)**: Unsubscribes a handler function from a specific event.
- **element.events.event_name += handler**: An alternative syntax for subscribing to events.
- **element.events.event_name -= handler**: An alternative syntax for unsubscribing from events.
### `DOMEventHandler`
For more control, use `DOMEventHandler` to manage event properties like `preventDefault`, `stopPropagation`, `stopImmediatePropagation`, and debouncing.
### Example
```python
def print_handler(e):
print(e)
def shout_handler(e):
print('!!!!!!!!')
print(e)
print('!!!!!!!!')
# Subscribe using .on()
element.on('click', print_handler)
# Subscribe using event attribute
element.events.click += shout_handler
# Unsubscribe using .off()
element.off('click', print_handler)
# Unsubscribe using event attribute
element.events.click -= shout_handler
# Using DOMEventHandler for dragover event
window.dom.document.events.dragover += DOMEventHandler(on_drag, prevent_default=True, stop_propagation=True, stop_immediate_propagation=True, debounce=500)
# Handling drop event with file information
window.dom.document.events.drop += lambda e: print(e['domTransfer']['files'][0])
```
```
--------------------------------
### Pyinstaller with Python SO on Linux
Source: https://pywebview.flowrl.com/guide/freezing.html
For Linux, if you encounter a `cannot find python3.xx.so error`, add the Python shared object to the pyinstaller binary list. Replace 'x' with your Python version.
```bash
pyinstaller main.py --add-data index.html:. --add-binary /usr/lib/x86_64-linux-gnu/libpython3.x.so:. --onefile
```
--------------------------------
### Element Visibility and Focus
Source: https://pywebview.flowrl.com/guide/dom.html
Controls the visibility and focus state of DOM elements.
```APIDOC
## Element Visibility and Focus
Manages the visibility and focus state of DOM elements.
### Methods
- **hide()**: Hides the element.
- **show()**: Shows the element.
- **toggle()**: Toggles the visibility of the element.
- **focus()**: Sets focus to the element.
- **blur()**: Removes focus from the element.
### Properties
- **visible** (boolean): Returns `True` if the element is visible, `False` otherwise.
- **focused** (boolean): Returns `True` if the element has focus, `False` otherwise.
### Example
```python
element.hide()
print(element.visible) # False
element.show()
print(element.visible) # True
element.toggle()
element.focus()
print(element.focused) # True
element.blur()
print(element.focused) # False
```
```
--------------------------------
### Access Exposed Python Functions from Javascript
Source: https://pywebview.flowrl.com/guide/interdomain.html
Shows how to call exposed Python functions from Javascript. The `pywebview.api` object is used, and it's recommended to wait for the `window.pywebviewready` event before accessing it.
```javascript
window.addEventListener('pywebviewready', () => {
pywebview.api.multiply(5, 3).then(result => {
console.log('Result from Python:', result);
}).catch(error => {
console.error('Error calling Python function:', error);
});
});
```
--------------------------------
### Run Javascript from Python
Source: https://pywebview.flowrl.com/guide/usage.html
Use `window.evaluate_js(code)` to execute Javascript from Python. It returns the result of the last line. For promises, use a callback. Errors raise `JavascriptException`. `window.run_js(code)` executes without returning a result.
```python
import webview
class Api():
def log(self, value):
print(value)
webview.create_window("Test", html="", js_api=Api())
webview.start()
```
--------------------------------
### Element Information and Modification
Source: https://pywebview.flowrl.com/guide/dom.html
Provides access to an element's properties like ID, classes, styles, and text content. Many properties can also be modified directly.
```APIDOC
## Element Information and Modification
Accesses and modifies properties of a DOM element.
### Properties
- **id** (string): The element's ID.
- **classes** (object): An object with methods `add`, `remove`, `toggle` to manage CSS classes.
- **style** (dict-like object): A dictionary-like object to manage inline styles.
- **tabindex** (integer): The element's tab index.
- **tag** (string): The element's tag name.
- **text** (string): The element's text content.
- **value** (string): The input element's value.
### Example
```python
# Get properties
print(element.id)
print(element.classes)
print(element.style['width'])
print(element.text)
# Set properties
element.id = 'new-id'
element.classes.add('green-text')
element.style['width'] = '200px'
element.text = 'New content'
element.value = 'Luna'
```
```
--------------------------------
### Advanced DOM Event Handling
Source: https://pywebview.flowrl.com/guide/dom.html
Utilize `DOMEventHandler` for fine-grained control over event behavior, including `preventDefault`, `stopPropagation`, and debouncing. The `drop` event provides file path information.
```python
window.dom.document.events.dragover += DOMEventHandler(on_drag, prevent_default=True, stop_propagation=True, stop_immediate_propagation=True, debounce=500)
```
```python
window.dom.document.events.drop += lambda e: print(e['domTransfer']['files'][0]) # print a full path of the dropped file
```
--------------------------------
### Exclude Modules with Pyinstaller
Source: https://pywebview.flowrl.com/guide/faq.html
When creating a frozen executable, use the `--exclude-module` option with Pyinstaller to prevent unnecessary dependencies from increasing the executable size.
```bash
pyinstaller --exclude-module PyQt
```
--------------------------------
### Access Global DOM Objects
Source: https://pywebview.flowrl.com/guide/dom.html
Directly access the `body`, `document`, and `window` objects from the `window.dom` interface for global DOM operations.
```python
window.dom.body
window.dom.document
window.dom.window
```
--------------------------------
### DOM Traversal
Source: https://pywebview.flowrl.com/guide/dom.html
Navigate the DOM tree using properties like `children`, `next`, `parent`, and `previous` to access related elements.
```python
element.children # return a list of element's children
element.next # return a next element in the DOM hierarchy or None
element.parent # return element's parent
element.previous # return a previous element in the DOM hierarchy or None
```
--------------------------------
### Subscribe to DOM Events
Source: https://pywebview.flowrl.com/guide/dom.html
Attach event handlers to DOM elements using `on()` or the `events` attribute. Events can be detached using `off()` or the `-=` operator.
```python
def print_handler(e):
print(e)
def shout_handler(e):
print('!!!!!!!!')
print(e)
print('!!!!!!!!')
element.on('click', print_handler)
element.events.click += shout_handler # these two ways to subscribe to an event are equivalent
element.off('click', print_handler)
element.events.click -= shout_handler # as well as these two
```
--------------------------------
### Element Traversal
Source: https://pywebview.flowrl.com/guide/dom.html
Allows navigation through the DOM hierarchy to access related elements such as children, parent, next, and previous siblings.
```APIDOC
## Traversal
Navigates the DOM tree relative to the current element.
### Properties
- **children** (list): Returns a list of the element's direct children.
- **next** (Element or None): Returns the next sibling element in the DOM hierarchy, or `None` if there is no next sibling.
- **parent** (Element): Returns the parent element.
- **previous** (Element or None): Returns the previous sibling element in the DOM hierarchy, or `None` if there is no previous sibling.
### Global Access
- `window.dom.body`: Accesses the `` element.
- `window.dom.document`: Accesses the `document` object.
- `window.dom.window`: Accesses the `window` object.
### Example
```python
print(element.children)
print(element.next)
print(element.parent)
print(element.previous)
print(window.dom.body)
```
```
--------------------------------
### Access and Modify Element Properties
Source: https://pywebview.flowrl.com/guide/dom.html
Read and write properties like `id`, `classes`, `style`, `text`, and `value` for DOM elements. Classes can be added, removed, or toggled.
```python
element.id # return element's id
element.classes # return a list like object of element's classes
element.style # return a dict like object of element's styles
element.tabindex # return element's tab index
element.tag # return element's tag name
element.text # return element's text content
element.value # return input element's value
```
```python
element.id = 'new-id'
element.classes.add('green-text') # add .green-text class
element.classes.remove('red-background') # remove .red-background class
element.classes.toggle('blue-border') # toggle .blue-border class
element.style['width'] = '200px'
element.tabindex = 108
element.text = 'New content'
element.value = 'Luna'
```
--------------------------------
### Manipulate Element
Source: https://pywebview.flowrl.com/guide/dom.html
Provides methods for copying, moving, removing, emptying, and appending DOM elements.
```APIDOC
## Manipulate Element
Performs various manipulation operations on DOM elements.
### Methods
- **copy(**parent=None, mode=ManipulationMode.LastChild, id=None**)**: Copies the element and appends it as a child to the specified parent. Returns the copied element.
- **move(**selector**)**: Moves the element to the specified selector as the last child. Returns the moved element.
- **remove()**: Removes the element from the DOM.
- **empty()**: Removes all child elements of the current element.
- **append(html)**: Appends new HTML content as a child to the current element.
### Example
```python
new_container = window.get_element('#new-container')
new_element = element.copy()
yet_another_element = new_element.copy(new_container, webview.dom.ManipulationMode.FirstChild, "new-id")
yet_another_element = yet_another_element.move('#new-container2')
yet_another_element.remove()
new_container.empty()
new_container.append('kick-ass content')
```
```
--------------------------------
### Expose Python Class Methods to Javascript
Source: https://pywebview.flowrl.com/guide/interdomain.html
Exposes methods of a Python class to Javascript via the `js_api` parameter. Callable methods become accessible in Javascript as `pywebview.api.method_name`. Nested classes are supported.
```python
import webview
class Api:
def greet(self, name):
return f"Hello, {name}!"
window = webview.create_window('JS API Example', 'index.html', js_api=Api())
webview.start()
```
--------------------------------
### Disable Auto-Opening DevTools
Source: https://pywebview.flowrl.com/guide/debugging.html
To prevent the web inspector from automatically opening, set `webview.settings['OPEN_DEVTOOLS_IN_DEBUG'] = False` before calling `webview.start()`.
```python
webview.settings['OPEN_DEVTOOLS_IN_DEBUG'] = False
```
--------------------------------
### Manipulate DOM Elements
Source: https://pywebview.flowrl.com/guide/dom.html
Perform operations such as copying, moving, removing, emptying, and appending elements. Elements can be copied to specific locations with optional new IDs.
```python
new_container = window.get_element('#new-container')
new_element = element.copy() # copies element as the parent's last child
yet_another_element = new_element.copy(new_container, webview.dom.ManipulationMode.FirstChild, "new-id") # copies element to #new-container as a first child
yet_another_element = yet_another_element.move('#new-container2') # moves element to #new-container2 as a last child
yet_another_element.remove() # remove element
new_container.empty() # empty #new-container from its children
new_container.append('kick-ass content') # append new DOM to #new-container
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.