File: README.md
pywebview is a lightweight native webview wrapper that allows to display HTML content in its own native GUI window. It gives you power of web technologies in your desktop application, hiding the fact that GUI is browser based. pywebview ships with a built-in HTTP server, DOM support in Python and window management functionality.
pywebview is available for Windows, macOS, Linux (GTK or QT) and Android. It uses native GUI for creating a web component window: WinForms on Windows, Cocoa on macOS and QT or GTK on Linux. If you choose to freeze your application, pywebview does not bundle a heavy GUI toolkit or web renderer with it keeping the executable size small.
pywebview provides advanced features like window manipulation functionality, event system, built-in HTTP server, native GUI elements like application menu and various dialogs, two way communication between Javascript โ Python and DOM support.
pywebview is created by Roman Sirokov.
Install
pip install pywebviewYou might need additional libraries. Refer to the installation page for details.
Hello world
import webview
webview.create_window('Hello world', 'https://pywebview.flowrl.com/hello')
webview.start()Explore pywebview further by reading documentation, exploring examples or contributing. If React is your thing, get started right away with React boilerplate.
Sponsors
Code Contributors
This project thrives thanks to the contributions of our community. [Learn how to contribute].
Consulting services
If your company is looking for support with pywebview or needs a hand with full-stack development, the author of pywebview is available for hire. As a VAT-registered EU based professional, I specialize in a wide range of technologies, including JavaScript/TypeScript, React/Vue, Python, GIS, SQL databases, API integration, CI/CD pipelines and cloud solutions. For inquiries about availability and pricing details, reach out to [email protected].
Donate
Become a financial contributor and help us sustain our community. More donation options are outlined on the Donating page.
File: docs/api/README.md
API
webview.active_window
webview.active_window()Get an instance of the currently active window
webview.create_window
webview.create_window(title, url=None, html=None, js_api=None, width=800, height=600,
x=None, y=None, screen=None, resizable=True, fullscreen=False,
min_size=(200, 100), hidden=False, frameless=False,
easy_drag=True, shadow=False, focus=True, minimized=False, maximized=False, menu=[],
on_top=False, confirm_close=False, background_color='#FFFFFF',
transparent=False, text_select=False, zoomable=False,
draggable=False, vibrancy=False, server=http.BottleServer, server_args={},
localization=None)Create a new pywebview window and returns its instance. Can be used to create multiple windows (except Android). Window is not shown until the GUI loop is started. If the function is invoked during the GUI loop, the window is displayed immediately.
title- Window titleurl- URL to load. If the URL does not have a protocol prefix, it is resolved as a path relative to the application entry point. Alternatively a WSGI server object can be passed to start a local web server.html- HTML code to load. If both URL and HTML are specified, HTML takes precedence.js_api- Expose a python object to the Javascript domain of the currentpywebviewwindow. Methods of thejs_apiobject can be invoked from Javascript by callingwindow.pywebview.api.<methodname>()functions. Exposed function return a promise that return once function returns. Only basic Python objects (like int, str, dict, ...) can be returned to Javascript.width- Window width in logical pixels. Default is 800px.height- Window height in logical pixels. Default is 600px.x- Window x coordinate in logical pixels. Default is centered.y- Window y coordinate in logical pixels. Default is centered.screen- Screen to display window on.screenis a screen instance returned bywebview.screens.resizable- Whether window can be resized. Default is Truefullscreen- Start in fullscreen mode. Default is Falsemin_size- a (width, height) tuple that specifies a minimum window size in logical pixels. Default is 200x100hidden- Create a window hidden by default. Default is Falseframeless- Create a frameless window. Default is False.easy_drag- Easy drag mode for frameless windows. Window can be moved by dragging any point. Default is True. Note that easy_drag has no effect with normal windows. To control dragging on an element basis, see drag area for details.shadow- Add window shadow. Default is False. Windows only.focus- Create a non-focusable window if False. Default is True.minimized- Display window minimizedmaximized- Display window maximizedmenu- A list ofMenuobjects to create a window specific menu. This menu overrides the application menu specified inwebview.start. Not supported on GTK.on_top- Set window to be always on top of other windows. Default is False.confirm_close- Whether to display a window close confirmation dialog. Default is Falsebackground_color- Background color of the window displayed before WebView is loaded. Specified as a hex color. Default is white.transparent- Create a transparent window. Not supported on Windows. Default is False. Note that this setting does not hide or make window chrome transparent. To hide window chrome setframelessto True.text_select- Enables document text selection. Default is False. To control text selection on per element basis, use user-select CSS property.zoomable- Enable document zooming. Default is Falsedraggable- Enable image and link object dragging. Default is Falsevibrancy- Enable window vibrancy. Default is False. macOS only.server- A custom WSGI server instance for this window. Defaults to BottleServer.server_args- Dictionary of arguments to pass through to the server instantiationlocalization- pass a localization dictionary for per window localization.
webview.start
webview.start(func=None, args=None, localization={}, gui=None, debug=False,
http_server=False, http_port=None, user_agent=None, private_mode=True,
storage_path=None, menu=[], server=http.BottleServer, ssl=False,
server_args={}, icon=None):Start a GUI loop and display previously created windows. This function must be called from a main thread.
func- function to invoke upon starting the GUI loop.args- function arguments. Can be either a single value or a tuple of values.localization- a dictionary with localized strings. Default strings and their keys are defined in localization.pygui- force a specific GUI. Allowed values arecef,qtorgtkdepending on a platform. See Web Engine for details.debug- enable debug mode. See Debugging for details.http_server- enable built-in HTTP server for absolute local paths. For relative paths HTTP server is started automatically and cannot be disabled. For each window, a separate HTTP server is spawned. This option is ignored for non-local URLs.http_port- specify a port number for the HTTP server. By default port is randomized.user_agent- change user agent string.private_mode- Control whether cookies and other persistant objects are stored between session. By default private mode is on and nothing is stored between sessions.storage_path- An optional location on hard drive where to store persistant objects like cookies and local storage. By default~/.pywebviewis used on *nix systems and%APPDATA%\pywebviewon Windows.menu- Pass a list of Menu objects to create an application menu. See this example for usage details.server- A custom WSGI server instance. Defaults to BottleServer.ssl- If using the default BottleServer (and for now the GTK backend), will use SSL encryption between the webview and the internal server. You need to havecryptographypip dependency installed in order to usessl. It is not installed by default.server_args- Dictionary of arguments to pass through to the server instantiationicon- path to application icon. Generally icon should be specified during bundling, but if you need to set it manually, you can use this parameter. Supported formats are.icoon Windows and.icnson macOS. On Linux support depends on the desktop environment, but generally.pngicons are supported.
Examples
webview.screens
webview.screensReturn a list of available displays (as Screen objects) with the primary display as the first element of the list.
Examples
webview.settings
webview.settings = {
'ALLOW_DOWNLOADS': False,
'ALLOW_FILE_URLS': True,
'DRAG_REGION_SELECTOR': 'pywebview-drag-region',
'DRAG_REGION_DIRECT_TARGET_ONLY': False,
'OPEN_EXTERNAL_LINKS_IN_BROWSER': True,
'OPEN_DEVTOOLS_IN_DEBUG': True,
'IGNORE_SSL_ERRORS': False,
'REMOTE_DEBUGGING_PORT': None,
'SHOW_DEFAULT_MENUS': True
}Additional options that override default behaviour of pywebview to address popular feature requests.
ALLOW_DOWNLOADSAllow file downloads. Disabled by default.ALLOW_FILE_URLSEnablefile://urls. Disabled by default.DRAG_REGION_SELECTORCSS selector for a drag region in easy drag mode. Default selector is.pywebview-drag-region.DRAG_REGION_DIRECT_TARGET_ONLYWhen set to True, only elements that directly match the drag region selector are draggable. When False, child elements of a drag region are also draggable. Default is False.IGNORE_SSL_ERRORSIgnore SSL errors. Disabled by default.OPEN_EXTERNAL_LINKS_IN_BROWSER. Opentarget=_blanklink in an external browser. Enabled by default.OPEN_DEVTOOLS_IN_DEBUGOpen devtools automatically in debug mode. Enabled by default.REMOTE_DEBUGGING_PORTEnable remote debugging when usingedgechromiumorqt. Disabled by default.SHOW_DEFAULT_MENUSShow default menus on Cocoa. Enabled by default.WEBVIEW2_RUNTIME_PATHPath to WebView2 runtime. You can use relative paths, which will be resolved relative to the application entry point with support of path resolution for most bundlers. If not set, the system installed runtime is used if present.
Examples
webview.token
webview.tokenA CSRF token property unique to the session. The same token is exposed as window.pywebview.token. See Security for usage details.
webview.dom
webview.dom.DOMEventHandler
DOMEventHandler(callback, prevent_default=False, stop_propagation=False, stop_immediate_propagation=False, debounce=0)A container for an event handler used to control propagation or default behaviour of the event. If debounce is greater than zero, Python event handler is debounced by a specified number of milliseconds. This can be useful for events like dragover and mouseover that generate a constant stream of events resulting in poor performance.
DOMEventHandler can be used to get a full path of droppped files in drop event on the Python side. The file path information is stored in event['dataTransfer']['files'][0]['pywebviewFullPath'] property of the event object. See this example for details.
Examples
element.events.click += DOMEventHandler(on_click, prevent_default=True, stop_propagation=True, stop_immediate_propagation=True)
element.events.mouseover += DOMEventHandler(on_click, debounce=500)webview.dom.ManipulationMode
Enum that sets the position of a manipulated DOM element. Possible values are:
LastChild- element is inserted as a last child of the targetFirstChild- element is inserted as a firt child of the targetBefore- element is inserted before the targetAfter- element is inserted after the targetReplace- element is inserted replacing the target
Used by element.append, element.copy, element.move and window.dom.create_element functions.
webview.Element
element.attributes
Get or modify element's attributes. attributes is a PropsDict dict-like object that implements most of dict functions. To add an attribute, you can simply assign a value to a key in attributes. Similarly, to remove an attribute, you can set its value to None.
Examples
element.attributes['id'] = 'container-id' # set element's id
element.attributes['data-flag'] = '1337'
element.attributes['id'] = None # remove element's id
del element.attributes['data-flag'] # remove element's data-flag attributeelement.classes
element.classesGet or set element's classes. classes is a ClassList list-like object that implements a subset of list functions like append, remove and clear. Additionally it has a toggle function for toggling a class.
Examples
element.classes = ['container', 'red', 'dotted'] # overwrite element's classes
element.classes.remove('red') # remove red class
element.classes.add('blue') # add blue class
element.classes.toggle('dotted')element.append
element.append(html, mode=webview.dom.ManipulationMode.LastChild)Insert HTML content to the element as a last child. To control the position of the new element, use the mode parameter. See Manipulation mode for possible values.
element.blur
element.blur()Blur element.
element.children
element.childrenGet element's children elements. Returns a list of Element objects.
element.copy
element.copy(target=None, mode=webview.dom.ManipulationMode.LastChild, id=None)Create a new copy of the element. target can be either another Element or a DOM selector string. If target is omitted, a copy is created in the current element's parent. To control the position of the new element, use the mode parameter. See Manipulation mode for possible values. The id parameter is stripped from the copy. Optionally you can set the id of the copy by specifying the id parameter.
element.empty
element.empty()Empty element by removing all its children.
element.events
element.eventsA container object of element's all DOM events, ie events.click, event.keydown. This container is dynamically populated and its contents depend on the events a node has. To subscribe to a DOM event, use the += syntax, e.g. element.events.click += callback. Similarly to remove an event listener use -=, eg. element.events.click -= callback. Callback can be either a function or an instance of DOMEventHandler if you need to control propagation of the event.
element.focus
element.focus()Focus element.
element.focused
element.focusedGet whether the element is focused.
element.hide
element.hide()Hide element by setting display: none.
element.id
element.idGet or set element's id. None if id is not set.
element.move
element.move(target, mode=webview.dom.ManipulationMode.LastChild)Move element to the target that can be either another Element or a DOM selector string. To control the position of the new element, use the mode parameter. See Manipulation mode for possible values.
Examples
element.next
element.nextGet element's next sibling. None if no sibling is present.
element.off
element.off(event, callback)Remove an event listener. Identical to element.event.event_name -= callback.
Examples
# these two are identical
element.off('click', callback_func)
element.events.click -= callback_funcelement.on
element.on(event, callback)Add an event listener to a DOM event. Callback can be either a function or an instance of DOMEventHandler if you need to control propagation of the event. Identical to element.event.event_name += callback.
Examples
# these two are identical
element.on('click', callback_func)
element.events.click += callback_funcelement.parent
element.parentGet element's parent Element or None if root element is reached.
element.previous
element.previousGet element's previous sibling. None if no sibling is present.
element.remove
element.remove()Remove element from DOM. Element object is not destroyed, but marked as removed. Trying to access any properties or invoke any functions of the element will result in a warning.
element.show
element.show()Show hidden element. If element was hidden with element.hide(), a previous display value is restored. Otherwise display: block is set.
element.style
Get or modify element's styles. style is a PropsDict dict-like object that implements most of dict functions. To add a style declraration, you can simply assign a value to a key in attributes. Similarly, to reset a declaration, you can set its value to None.
Examples
element.style['width'] = '100px' # set element's width to 100px
element.style['display'] = 'flex' # set element's display property to flex
element.style['width'] = None # reset width to auto
del element.attributes['display'] # reset display property to blockelement.tabindex
element.tabindexGet or set element's tabindex.
element.tag
element.tagGet element's tag name.
element.text
element.textGet or set element's text content.
element.toggle
element.toggle()Toggle element's visibility.
element.value
element.valueGet or set element's value. Applicable only to input elements that have a value.
element.visible
element.visibleGet whether the element is visible.
webview.Menu
Used to create an application menu. See this example for usage details.
menu.Menu
Menu(title, items=[]).
Instantiate to create a menu that can be either top level menu or a nested menu. title is the title of the menu and items is a list of actions, separators or other menus. If title is "__app__", then the menu is treated as an application menu on macOS and ignored on other platforms.
menu.MenuAction
MenuAction(title, function)
Instantiate to create a menu item. title is the name of the item and function is a callback that should be called when menu action is clicked.
menu.MenuSeparator
MenuSeparator()
Instantiate to create a menu separator.
webview.Screen
Represents a display found on the systems. A list of Screen objects is returned by webview.screens property.
All coordinate and dimension properties (x, y, width, height) are in logical pixels. Use the physical_* properties to access physical pixel values.
screen.height
screen.heightGet display height in logical pixels.
screen.width
screen.widthGet display width in logical pixels.
screen.x
screen.xGet X coordinate of the top-left corner of the display in logical pixels.
screen.y
screen.yGet Y coordinate of the top-left corner of the display in logical pixels.
screen.scale
screen.scaleGet the scale factor (DPI scale) for this display. For example, a value of 2.0 indicates a Retina or HiDPI display with 2x scaling, while 1.0 indicates a standard DPI display.
screen.physical_width
screen.physical_widthGet display width in physical pixels. Equal to width * scale.
screen.physical_height
screen.physical_heightGet display height in physical pixels. Equal to height * scale.
screen.physical_x
screen.physical_xGet X coordinate of the top-left corner of the display in physical pixels. Equal to x * scale.
screen.physical_y
screen.physical_yGet Y coordinate of the top-left corner of the display in physical pixels. Equal to y * scale.
screen.dpi
screen.dpiGet the DPI (dots per inch) for this display. Calculated as scale * 96. Standard DPI is 96, so a 2x scaled display would report 192 DPI.
webview.Window
Represents a window that hosts webview. window object is returned by create_window function.
window.title
window.titleGet or set title of the window.
window.on_top
window.on_topGet or set whether the window is always on top.
window.x
window.xGet X coordinate of the top-left corner of the window in logical pixels.
window.y
window.yGet Y coordinate of the top-left corner of the window in logical pixels. For macOS Y-coordinate is measured from the bottom of the screen, but for consistency with other platforms it is converted to a coordinate system with Y=0 at the top of the screen.
window.width
window.widthGet width of the window in logical pixels.
window.height
window.heightGet height of the window in logical pixels.
window.clear_cookies
window.clear_cookies()Clear all the cookies including HttpOnly ones.
Example
window.create\_confirmation\_dialog
window.create_confirmation_dialog(title, message)Create a confirmation (Ok / Cancel) dialog.
window.create\_file\_dialog
window.create_file_dialog(dialog_type=FileDialog.OPEN, directory='', allow_multiple=False, save_filename='', file_types=())Create an open file (webview.FileDialog.OPEN), open folder (webview.FileDialog.FOLDER) or save file (webview.FileDialog.OPEN.SAVE) dialog.
Return a tuple of selected files, None if cancelled.
allow_multiple=Trueenables multiple selection.directoryInitial directory.save_filenameDefault filename for save file dialog.file_typesA tuple of supported file type strings in the open file dialog. A file type string must follow this format"Description (*.ext1;*.ext2...)".
If the argument is not specified, then the "All files (*.*)" mask is used by default. The 'All files' string can be changed in the localization dictionary.
Examples
window.destroy
window.destroy()Destroy the window.
window.evaluate_js
window.evaluate_js(script, callback=None)Execute Javascript code. The last evaluated expression is returned. If callback function is supplied, then promises are resolved and the callback function is called with the result as a parameter. Javascript types are converted to Python types, eg. JS objects to dicts, arrays to lists, undefined to None. DOM nodes are serialized using custom serialization. Functions are omitted and circular references are converted to the [Circular Reference] string literal. webview.error.JavascriptException is thrown if executed codes raises an error.
r-strings is a recommended way to load Javascript. Note that the evaluate_js employs eval, which will fail if unsafe-eval CSP is set. Alternatively you may use window.run_js(code) that executes Javascript code as is without returning a result.
window.expose
Expose a Python function or functions to JS API. Functions are exposed as window.pywebview.api.func_name
window.get_cookies
window.get_cookies()Return a list of all the cookies set for the current website (as SimpleCookie).
window.get_current_url
window.get_current_url()Return the current URL. None if no url is loaded.
window.get_elements
window.get_elements(selector)DEPRECATED. Use window.dom.get_elements instead.
window.hide
window.hide()Hide the window.
window.load_css
window.load_css(css)Load CSS as a string.
window.load_html
window.load_html(content, base_uri=base_uri())Load HTML code. Base URL for resolving relative URLs is set to the directory the program is launched from. Note that you cannot use hashbang anchors when HTML is loaded this way.
window.load_url
window.load_url(url)Load a new URL.
window.maximize
window.maximize()Maximize window.
window.minimize
window.minimize()Minimize window.
window.move
window.move(x, y)Move window to a new position. x and y are in logical pixels.
window.native
window.native.Handle # get application window handle on WindowsGet a native window object. This can be useful for applying custom styling to the window. Object type depends on the platform
System.Windows.Form - WindowsAppKit.NSWindow - macOSGtk.ApplicationWindow - GTKQMainWindow - QTkivy.uix.widget.Widget - Android
The native property is available after the before_show event is fired.
You can also each platform's WebView object via window.native.webview. WebView's types are as follows.
Microsoft.Web.WebView2.WinForms.WebView2 - Windows / EdgeChromiumSystem.Windows.Forms.WebBrowser - Windows / MSHTMLWebKit.WKWebView - macOSgi.repository.WebKit2.WebView - GTKQtWebEngineWidgets.QWebEngineView / QtWebKitWidgets.QWebView- QTandroid.webkit.WebView - Android
window.resize
window.resize(width, height, fix_point=FixPoint.NORTH | FixPoint.WEST)Resize window. width and height are in logical pixels. Optional parameter fix_point specifies in respect to which point the window is resized. The parameter accepts values of the webview.window.FixPoint enum (NORTH, SOUTH, EAST, WEST)
window.restore
window.restore()Restore minimized window.
window.run_js
window.run_js('document.body.style.color = "deepred"')Execute Javascript as is without wrapping it in eval and helper code. This function does not return a result.
window.set_title
window.set_title(title)DEPRECATED. Use window.title instead. Change the title of the window.
window.show
window.show()Show the window if it is hidden. Has no effect otherwise
window.toggle_fullscreen
window.toggle_fullscreen()Toggle fullscreen mode on the active monitor.
window.dom.body
window.bodyGet document's body as an Element object
window.dom.create_element
window.create_element(html, parent=None, mode=webview.dom.ManipulationMode.LastChild)Insert HTML content and returns the Element of the root object. parent can be either another Element or a DOM selector string. If parent is omited, created DOM is attached to document's body. To control the position of the new element, use the mode parameter. See Manipulation mode for possible values.
window.dom.document
window.documentGet window.document of the loaded page as an Element object
window.dom.get_element
window.get_element(selector: str)Get a first Element matching the selector. None if not found.
window.dom.get_elements
window.get_elements(selector: str)Get a list of Element objects matching the selector.
window.dom.window
Get DOM document's window window as an Element object
Window events
Window object exposes various lifecycle and window management events. To subscribe to an event, use the += syntax, e.g., window.events.loaded += func. Duplicate subscriptions are ignored, and the function is invoked only once for duplicate subscribers. To unsubscribe, use the -= syntax, e.g., window.events.loaded -= func. To access the window object from the event handler, supply the window parameter as the first positional argument of the handler. Most window events are asynchronous, and event handlers are executed in separate threads. The before_show and before_load events are synchronous and block the main thread until handled.
window.events.before_show
This event is fired just before pywebview window is shown. This is the earliest event that exposes window.native property. This event is blocking.
window.events.before_load
The event is fired right before pywebview code is injected into the page. The event roughly corresponds to DOMContentLoaded DOM event. This event is blocking.
window.events.closed
The event is fired just before pywebview window is closed.
window.events.closing
The event is fired when pywebview window is about to be closed. If confirm_close is set, then this event is fired before the close confirmation is displayed. If event handler returns False, the close operation will be cancelled.
window.events.initialized
The event is fired right after GUI is chosen and HTTP server is started (if applicable). The first parameter renderer has a value of the chosen GUI library / web renderer. If event handler returns False, the window creation will be cancelled and GUI loop will not be started (for windows created before the GUI loop is started). This event is blocking.
window.events.loaded
The event is fired when DOM is ready.
window.events.maximized
The event is fired when window is maximized (fullscreen on macOS)
window.events.minimized
The event is fired when window is minimized.
window.events.moved
The event is fired when window is moved.
window.events.request_sent
The event is fired when a HTTP request is sent. The event is emitted for every HTTP request, except on macOS where it is emitted only for the main document.
The event handler can accept a single argument - a Request object that contains the following properties:
url- URL of the requestmethod- HTTP methodheaders- HTTP request headers as a dictionary. If you mutate mutate headers, modified headers will be used for the request.
window.events.response_received
The event is fired when a HTTP response is received. The event is emitted for every HTTP response, except on macOS where it is emitted only for the main document.
The event handler can accept a single argument - a Response object that contains the following properties:
url- URL of the responsestatus- HTTP status codeheaders- HTTP response headers as a dictionary
Not supported on QT.
window.events.restored
The event is fired when window is restored.
window.events.resized
The event is fired when pywebview window is resized. Event handler can either have no or accept (width, height) arguments.
window.events.shown
The event is fired when pywebview window is shown.
window.state
An observable class object that holds the state shared between Python and Javascript. Setting any property of this state will result in pywebview.state having updated on the Javascript side and vice versa. Both class (state.) and index (state['property']) notations are supported. Object mutations are not detected. State is unique to a window and is preserved between page loads. State changes fire events that can be subscribed as pywebview.state += lambda event_type, key, value: pass. event_type is either change or delete. key is a property name and value for its value (None for delete events). See also Javascript state events
Javascript API
pywebview create a global Javascript object window.pywebview that has following properties
window.pywebview
A global Javascript object that exposes the following properties:
api- A namespace for Python functions exposed viawindow.exposeorjs_apiargument.platform- Current renderer in use.token- A CSRF token unique to the session that matcheswebview.tokenon the Python side.state- A shared state object between Python and Javascript.
DOM events
pywebviewready
pywebview exposes a window.pywebviewready event that is fired after window.pywebview object is fully created.
State events
pywebview.state is an EventTarget object that fires two events change and delete. To subscribe to an event, usepywebview.state.addEventListener('change', (e) => {}) or pywebview.state.addEventListener('delete', (e) => {}). State change is stored in the event.detail object in form of { key, value }
Drag area
With a frameless pywebview window, A window can be moved or dragged by adding a special class called pywebview-drag-region to any element.
Now window can be moved by dragging this DIV.The magic class name can be overriden by re-assigning the webview.settings['DRAG_REGION_SELECTOR'] property.
File: docs/blog/pywebview5.md
5.0 has landed
I am happy to announce the release of pywebview 5. The new version introduces three major features: Android support, DOM manipulation and application settings. For a full changelog, see here.
If you are not familiar with pywebview, it is a Python library that lets you to build GUI for your Python program using HTML, CSS and Javascript. Available for Windows, macOS, Linux and Android. pywebview can be installed with
pip install pywebviewAndroid
You can now run your pywebview on Android devices. Mobile experience brings its own limitations though. There is no window manipulation, multi-window or file dialog support. Otherwise, it works same as on other platforms. Head over to Freezing for details how to package your app for Android.
DOM
With DOM support you can perform jQuery like DOM manipulation, traversal and event handling straight from Python. You can access and modify element's attributes, style and classes as well. A new Element object represents a DOM node in Python. It is returned by window.dom.get_element, window.dom.get_elements and window.dom.create_element. Body, document and window are conviently exposed as window.dom.body, window.dom.document and window.dom.body respectively. The new Javascript serializer allows you to serialize more Javascript object types and handles circular dependencies, so
Here is a toy example of the new API.
window.dom.document.events.scroll += lambda e: print(window.dom.window.node['scrollY'])
button = window.dom.create_element('Button', window.dom.body)
button.style['width'] = '200px'
button.attributes = { 'disabled': False }
button.events.click += click_handler
button.classes.toggle('hidden')See events, manipulation, traversal for complete examples.
A much requested feature is a full file path support for drag and drop operations. pywebview enhances DropEvent by introducing event['dataTransfer']['files'][0]['pywebviewFullPath'] that has full absolute path of a dropped file(s). The full path is available only on Python's side.
Application settings
pywebview is rather opinionated on how default experience should be. Over the years, I have received numerous feature requests asking to change the default behaviour, which is now possible with application settings. The new version introduces webview.settings dictionary with following options.
webview.settings = {
'ALLOW_DOWNLOADS': False, # Allow file downloads
'ALLOW_FILE_URLS': True, # Allow access to file:// urls
'OPEN_EXTERNAL_LINKS_IN_BROWSER': True, # Open target=_blank links in an external browser
'OPEN_DEVTOOLS_IN_DEBUG': True, # Automatically open devtools when `start(debug=True)`.
}Application settings must be set before invoking webview.start() to have an effect.
Learn more
Interested in learning more? Head over to usage guide, API reference and examples
Support the project
pywebview is largely an one-man project, which gets updated sporadically whenever time permits. Any help is appreciated and the best way to contribute is submitting a pull request. Bug fixes are always welcomed. If you wish to submit a new feature, please create an issue and discuss it beforehand. Check out the contributing guide to get started.
If you find pywebview useful and would like to see it developed in the future, considering sponsoring it. If you represent a company, consider becoming a sponsor to get exposure for your company and connect with Python developers.
<a href="https://github.com/sponsors/r0x0r">
</a>
<a href="https://opencollective.com/pywebview/donate" target="_blank">
</a>
<a href="https://www.patreon.com/bePatron?u=13226105" data-patreon-widget-type="become-patron-button">
</a>
<a href="http://bit.ly/2eg2Z5P" target="_blank">
</a>File: docs/blog/README.md
Blog
2025-08-08 pywebview 6
Another major installment with pywebview 6 featuring new state management, network event handling and window specific menus.
Read more
2024-03-08 pywebview 5
pywebview 5 has landed with Android support and DOM.
Read more
2019-07-11 Introducing pywebview 3.0
pywebview has reached version 3.0 and has a number of breaking changes.
Read more
File: docs/contributing/bug_reporting.md
Bug reporting
If you think you found a bug, verify following steps first
- Does the bug occur in a default browser? If so, the problem is with your code, not pywebview
- Are you using the latest master? Bug fixes are merged into the master and it may take a while until a new release is deployed to Pypi.
- Has it been reported already?
If you verified all the three points and are sure that the issue is caused by pywebview, feel free to submit a new issue. Please remember to specify under which operating system the bug occurs, as well as with other relevant information. In case of Linux, specify a distro you are using.
File: docs/contributing/development.md
Development
Before you get busy coding a new feature, create an issue and discuss the details in the issue tracker.
Environment set-up
This guide assumes you have a GitHub account, as well as Python 3, virtualenv and Git installed. The guide is written for Bash, for Windows you can use for example Bash bundled with Git.
- Fork pywebview
- Clone your forked repository
git clone https://github.com//pywebview
cd pywebview- Create a virtual environment
virtualenv -p python3 venv
source venv/bin/activate
pip install -e ".[dev]"
pip install pytest- Set up pre-commit hooks
pre-commit install- Hello world
python examples/simple_browser.pyDevelopment work-flow
- Create and checkout a new branch
git checkout -b new-branch masterMake your changes
Format and lint your code (this happens automatically with pre-commit)
# Manual formatting and linting (optional, pre-commit does this automatically)
ruff check --fix .
ruff format .- Run tests
pytest tests- Commit and push your work
git add .
git commit -m "Your commit message goes here" # Pre-commit hooks will run automatically
git push -u origin new-branchTesting
pywebview uses pytest for testing.
To run all the tests in the project root directory
pytest testsTo run a specific test
pytest tests/test_simple_browser.pyTests cover only trivial mistakes, syntax errors, exceptions and such. In other words there is no functional testing. Each test verifies that a pywebview window can be opened and exited without errors when run under different scenarios. Sometimes test fail / stuck randomly. The cause of the issue is not known, any help on resolving random fails is greatly appreciated.
Code Formatting and Linting
pywebview uses Ruff for code formatting and linting, along with pre-commit hooks to automatically enforce code quality standards.
Pre-commit Hooks
Pre-commit hooks are automatically installed when you run pre-commit install during setup. They will run automatically before each commit to:
- Fix import sorting
- Apply consistent code formatting (single quotes, line length, etc.)
- Check for large files, trailing whitespace, and YAML syntax
- Run linting checks and apply automatic fixes where possible
Ruff Configuration
The project uses the following Ruff configuration (defined in pyproject.toml):
- Line length: 100 characters
- Quote style: Single quotes for strings
- Import sorting: Enabled with
webviewas a known first-party package - Target Python version: 3.7+
- Enabled rules: Pyflakes (F), pycodestyle (E4, E7, E9), isort (I), and pyupgrade (UP)
Manual Formatting
While pre-commit hooks handle formatting automatically, you can also run formatting manually:
# Check for linting issues and apply fixes
ruff check --fix .
# Format code
ruff format .
# Run all pre-commit hooks manually
pre-commit run --all-filesCode Style Guidelines
- Use single quotes for strings (unless the string contains single quotes)
- Maximum line length of 100 characters
- Follow PEP 8 conventions
- Use f-strings instead of
.format()or%formatting where possible - Remove unused imports and variables
- Use
isinstance()instead oftype()comparisons
Learning
Windows
macOS
- pyobjc. Converting Objective C syntax to Python can be tricky at first. Be sure to check out the pyobjc intro.
- AppKit
- WebKit
Linux
Qt
File: docs/contributing/documentation.md
Documentation
One way to contribute is to improve documentation on this side. Each page has a 'Help us improve this page' link at the bottom of the page. By clicking the link you can create a pull request with your changes. You need a Github account to edit pages.
File: docs/contributing/donating.md
Donating
Recurrring pledge
Recurring pledges come perks, like getting email support or featuring your name or logo in the project repository
<a href="https://www.patreon.com/bePatron?u=13226105" data-patreon-widget-type="become-patron-button">
</a>
<a href="https://opencollective.com/pywebview/donate" target="_blank">
</a>One-time donations
We accept donations via Paypal
<a href="http://bit.ly/2eg2Z5P" target="_blank">
</a>File: docs/contributing/README.md
Thanks for considering contributing to pywebview.
pywebview is a small-time project, which gets updated sporadically whenever time permits. Any help is appreciated and the best way to contribute is submitting a pull request. Bug fixes are always welcome. If you wish to submit a new feature, please create an issue and discuss it beforehand.
If you found a bug and want to report it, please test it first in a web-browser that is used by default for your operating system to see if the problem is with your code, rather than pywebview. Do not forget to specify on which platform and pywebview version it occurs.
To support pywebview financially, consider sponsoring the project. Pywebview has no corporate backing and financial help is welcomed to keep the project alive.
<a href="https://www.patreon.com/bePatron?u=13226105" data-patreon-widget-type="become-patron-button">
</a>
<a href="https://opencollective.com/pywebview/donate" target="_blank">
</a>For other ways to donate refer to the donation page.