WebView
Display web content in a WebView to be shown in your Flet apps.
It is powered by the webview_all Flutter package.
Platform Support
| Platform | Windows | macOS | Linux | iOS | Android | Web |
|---|---|---|---|---|---|---|
| Supported | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Usage
Add flet-webview to your project dependencies:
- uv
- pip
uv add flet-webview
pip install flet-webview
Requirements
Windows
The Microsoft Edge WebView2 Runtime must be installed on the machine running the app. It ships with Windows 11 and is present on most Windows 10 installations.
When building an app that uses this control, flet build windows downloads NuGet and
the WebView2 SDK from nuget.org, so the build machine needs
access to it.
Linux
libwebkit2gtk-4.1-0 must be installed on the machine running the app, and
libwebkit2gtk-4.1-dev on the machine building it. Both are available from Debian 12
and Ubuntu 22.04 (with current updates) onward, so apps using this control do not run
on older releases. See Linux system libraries
for the other packages and distributions.
When running an app with flet run, select the
full desktop flavor: the default
light flavor does not include this control.
Web
The page is shown in an <iframe>, and Flet's web server (flet run --web,
flet serve) sends a Cross-Origin-Embedder-Policy: require-corp header. A page
from another origin therefore stays blank unless it allows being embedded and sends
both a Cross-Origin-Resource-Policy: cross-origin and a Cross-Origin-Embedder-Policy
header, which most sites do not.
JavaScript, the page title, scrolling, console messages and alerts are available
only for same-origin pages and for HTML loaded with load_html().
Example
WebView
import flet as ft
import flet_webview as fwv
def main(page: ft.Page):
page.add(
ft.SafeArea(
expand=True,
content=fwv.WebView(
url="https://flet.dev",
on_page_started=lambda _: print("Page started"),
on_page_ended=lambda _: print("Page ended"),
on_web_resource_error=lambda e: print("WebView error:", e.data),
expand=True,
),
)
)
if __name__ == "__main__":
ft.run(main)
Troubleshooting
NET::ERR_CLEARTEXT_NOT_PERMITTED Error
If you run into the NET::ERR_CLEARTEXT_NOT_PERMITTED error in Android, then the app you’re using is trying to access a web page that wants to transmit cleartext or unsecured information. Android blocks apps from doing this in order to avoid compromising user data.
For more details, see this and this.
To fix it, your app's configuration (precisely, the manifest application attributes) needs to be modified as follows:
- pyproject.toml
[tool.flet.android.manifest_application]
usesCleartextTraffic = "true"
Description
Easily load webpages while allowing user interaction.
- On Windows this control requires the Edge WebView2 runtime, which ships with Windows 11 and is present on most Windows 10 installations.
- On Linux it requires
libwebkit2gtk-4.1-0, which is available from Debian 12 and Ubuntu 22.04 (with current updates) onward. - On Linux the WebView is a native GTK widget rather than a Flutter
texture: other controls cannot be drawn over it, and a scale, rotation
or skew transform hides it entirely. Rectangular clips and the rounded
corners of a
Cardapply to it, but other clips, such as aContainerwithborder_radiusor a circularshape, hide it entirely. - On web the page is shown in an
<iframe>. Pages that forbid being embedded, and pages from another origin that do not allow embedding under theCross-Origin-Embedder-Policy: require-corpheader Flet's web server sends, stay blank. - On web the browser keeps the app from scripting or observing pages
from another origin, so JavaScript, the page title, scrolling, console
messages and alerts are available only for same-origin pages and for
HTML loaded with
load_html.
Inherits: LayoutControl
Properties
bgcolor- Defines the background color of the WebView.prevent_links- List of url-prefixes that should not be followed/loaded/downloaded.url- The URL of the web page to load.
Events
on_console_message- Fires when a log message is written to the JavaScript console.on_javascript_alert_dialog- Fires when the web page attempts to display a JavaScript alert() dialog.on_page_ended- Fires when all the webview page loading processes are ended.on_page_started- Fires soon as the first loading process of the webview page is started.on_progress- Fires when the progress of the webview page loading is changed.on_scroll- Fires when the web page's scroll position changes.on_url_change- Fires when the URL of the webview page is changed.on_web_resource_error- Fires when there is error with loading a webview page resource.
Methods
can_go_back- Whether there's a back history item.can_go_forward- Whether there's a forward history item.clear_cache- Clears all caches used by the WebView.clear_local_storage- Clears the local storage used by the WebView.disable_zoom- Disables zooming using the on-screen zoom controls and gestures.enable_zoom- Enables zooming using the on-screen zoom controls and gestures.get_current_url- Gets the current URL that the WebView is displaying orNoneif no URL was ever loaded.get_title- Get the title of the currently loaded page.get_user_agent- Get the value used for the HTTPUser-Agent:request header.go_back- Goes back in the history of the webview, ifcan_go_back()isTrue.go_forward- Goes forward in the history of the webview, ifcan_go_forwardisTrue.load_file- Loads the provided local file.load_html- Loads the provided HTML string.load_request- Makes an HTTP request and loads the response in the webview.reload- Reloads the current URL.run_javascript- Runs the given JavaScript in the context of the current page.scroll_by- Scrolls by the provided number of webview pixels.scroll_to- Scrolls to the provided position of webview pixels.set_javascript_mode- Sets the JavaScript mode of the WebView.
Properties
bgcolorclass-attributeinstance-attribute
bgcolor: ColorValue | None = NoneDefines the background color of the WebView.
On macOS this colors only the area around the page, which shows when scrolling past its edges.
prevent_linksclass-attributeinstance-attribute
prevent_links: list[str] | None = NoneList of url-prefixes that should not be followed/loaded/downloaded.
- On Windows, while this list is not empty, every allowed navigation is
restarted as a
GETrequest, so a form submitted withPOSTloses its data. - On web only the pages the app loads itself are checked, not links followed inside the page.
urlclass-attributeinstance-attribute
url: str | None = NoneThe URL of the web page to load.
Changing it loads the new URL. To load the same URL again, call
reload or load_request.
A file:// URL pointing to a local file loads that file's sibling
assets (scripts, stylesheets, images) as well, and is equivalent to
calling load_file with the same file once this control is
mounted. It is not supported on web.
Events
on_console_messageclass-attributeinstance-attribute
on_console_message: (
EventHandler[WebViewConsoleMessageEvent] | None
) = NoneFires when a log message is written to the JavaScript console.
- On Windows, iOS and macOS a handler set after the control was added to the page receives messages from the next page loaded.
- On Linux
severity_levelis alwaysLOG. - On Android
console.info()messages have theLOGseverity level. - On web only messages logged after
on_page_endedfired are delivered.
on_javascript_alert_dialogclass-attributeinstance-attribute
on_javascript_alert_dialog: (
EventHandler[WebViewJavaScriptEvent] | None
) = NoneFires when the web page attempts to display a JavaScript alert() dialog.
- Not supported on Windows, where Edge WebView2 always shows its own alert dialog.
- On iOS and macOS
alert()shows nothing unless this handler is set. - Setting this handler replaces the built-in alert dialog on Android, Linux and web, so the app becomes responsible for showing the message. The built-in dialog stays off after the handler is removed.
- On web
alert()does not block the page's script while this handler is set, and an alert raised beforeon_page_endedfired still opens the browser's dialog.
on_page_endedclass-attributeinstance-attribute
on_page_ended: ControlEventHandler[WebView] | None = NoneFires when all the webview page loading processes are ended.
The data property of the event handler argument is of type
str and contains the URL.
- On web this also fires when the browser refused to show the page.
- On web with the
canvaskitrenderer, whileon_scrollis set, this does not fire for a page from another origin or for aPOSTresponse.
on_page_startedclass-attributeinstance-attribute
on_page_started: ControlEventHandler[WebView] | None = (
None
)Fires soon as the first loading process of the webview page is started.
The data property of the event handler argument is of type
str and contains the URL.
On web this fires only for the pages the app loads itself, not for links followed inside the page.
on_progressclass-attributeinstance-attribute
on_progress: ControlEventHandler[WebView] | None = NoneFires when the progress of the webview page loading is changed.
The data property of the event handler argument is of type
int and contains the progress value.
- On Windows and web the progress is only ever
0or100. - On web with the
canvaskitrenderer, whileon_scrollis set, a page from another origin reports only0, andon_page_endeddoes not fire for it.
on_scrollclass-attributeinstance-attribute
on_scroll: EventHandler[WebViewScrollEvent] | None = NoneFires when the web page's scroll position changes.
- Not supported on macOS.
- On web it fires only for same-origin pages and HTML loaded with
load_html. - On web with the
canvaskitrenderer, setting this handler keepson_page_endedfrom firing for pages from another origin and forPOSTresponses.canvaskitis the default for static web apps, and the rendererautopicks in browsers not based on Chromium. - On Android
xandyare physical pixels: the page'swindow.scrollXandwindow.scrollYmultiplied bywindow.devicePixelRatio.
on_url_changeclass-attributeinstance-attribute
on_url_change: ControlEventHandler[WebView] | None = NoneFires when the URL of the webview page is changed.
The data property of the event handler argument is of type
str and contains the new URL.
On web, after a link is followed to another origin, this reports the last URL it could read, usually that of the page the app last loaded.
on_web_resource_errorclass-attributeinstance-attribute
on_web_resource_error: (
ControlEventHandler[WebView] | None
) = NoneFires when there is error with loading a webview page resource.
The data property of the event handler argument is of type
str and contains the error message.
- It also fires when
urlcannot be loaded, for example a URL without a scheme. - It also fires for a certificate error, and the page is not loaded. On web the browser handles certificate errors itself.
- On web it otherwise fires only for requests made with
POST. The browser does not report why a page shown in an<iframe>failed to load.
Methods
can_go_backasync
can_go_back() -> boolWhether there's a back history item.
On web the history contains only the pages the app loaded itself.
Returns:
- bool -
Trueif there is a back history item,Falseotherwise.
can_go_forwardasync
can_go_forward() -> boolWhether there's a forward history item.
On web the history contains only the pages the app loaded itself.
Returns:
- bool -
Trueif there is a forward history item,Falseotherwise.
clear_cacheasync
clear_cache()Clears all caches used by the WebView.
The following caches are cleared:
- Browser HTTP Cache
- Cache API caches. Service workers tend to use this cache.
- Application cache
- Not supported on web, where the WebView shares its caches with the app itself.
- On Windows and Linux only the HTTP cache is cleared.
Raises:
- FletUnsupportedPlatformException - If invoked on web.
clear_local_storageasync
clear_local_storage()Clears the local storage used by the WebView.
- Not supported on web, where the WebView shares its storage with the app itself.
- On Windows this also clears IndexedDB and Cache API storage, for every WebView of the app.
Raises:
- FletUnsupportedPlatformException - If invoked on web.
get_current_urlasync
get_current_url() -> str | NoneGets the current URL that the WebView is displaying or None
if no URL was ever loaded.
On web, after a link is followed to another origin, this returns the last URL it could read, usually that of the page the app last loaded.
Returns:
- str | None - The current URL that the WebView is displaying or
Noneif no URL was ever loaded.
get_titleasync
get_title() -> str | NoneGet the title of the currently loaded page.
On web this is None for a page from another origin.
Returns:
- str | None - The title of the currently loaded page.
get_user_agentasync
get_user_agent() -> str | NoneGet the value used for the HTTP User-Agent: request header.
On web this is the user agent of the browser running the app.
Returns:
- str | None - The value used for the HTTP
User-Agent:request header.
go_backasync
go_back()Goes back in the history of the webview, if can_go_back() is True.
On web the history contains only the pages the app loaded itself.
go_forwardasync
go_forward()Goes forward in the history of the webview,
if can_go_forward is True.
On web the history contains only the pages the app loaded itself.
load_fileasync
load_file(path: str)Loads the provided local file.
- Not supported on web.
- On Windows the page is opened from its
file://URL. It can load the stylesheets, scripts and images it links to, but it cannot read local files withfetch()orXMLHttpRequest, or load JavaScript modules (<script type="module">).
Parameters:
- path (str) - The absolute path to the file.
Raises:
- FletUnsupportedPlatformException - If invoked on web.
load_htmlasync
load_html(
value: str, base_url: str | None = None
) -> SelfLoads the provided HTML string.
On web the HTML runs with the app's own origin, so its scripts can read and change the app's storage and cookies. Load only HTML you trust there.
Parameters:
- value (str) - The HTML string to load.
- base_url (str | None, default:
None) - The base URL to use when resolving relative URLs within the value. May be afile://URL, in which case the referenced local files are made readable to the webview, except on Windows and web.
load_requestasync
load_request(
url: str, method: RequestMethod = RequestMethod.GET
)Makes an HTTP request and loads the response in the webview.
Parameters:
- url (str) - The URL to load. A
file://URL is loaded as a local file, the same wayload_filedoes, except on web. - method (RequestMethod, default:
RequestMethod.GET) - The HTTP method to use. Ignored forfile://URLs.
- On Linux a
POSTrequest is sent outside the WebView and its response is then shown in it, so a failed request raises an error rather than firingon_web_resource_error. - On web a
POSTrequest is sent by the app itself, so the browser's cross-origin (CORS) rules apply to it. - On Windows a
POSTrequest fails and fireson_web_resource_error, because it is sent without a body.
reloadasync
reload()Reloads the current URL.
On web, after a link was followed to another origin, this reloads the last page whose URL it could read instead.
run_javascriptasync
run_javascript(value: str)Runs the given JavaScript in the context of the current page.
Parameters:
- value (str) - The JavaScript code to run.
On web this works only for a same-origin page or HTML loaded with
load_html.
scroll_byasync
scroll_by(x: int, y: int)Scrolls by the provided number of webview pixels.
- Not supported on macOS.
- On Android the amounts are physical pixels, so the page scrolls by
ydivided bywindow.devicePixelRatioCSS pixels. - On web this works only for a same-origin page or HTML loaded with
load_html.
Parameters:
- x (int) - The number of pixels to scroll by on the x-axis.
- y (int) - The number of pixels to scroll by on the y-axis.
Raises:
- FletUnsupportedPlatformException - If invoked on macOS.
scroll_toasync
scroll_to(x: int, y: int)Scrolls to the provided position of webview pixels.
- Not supported on macOS.
- On Android the position is in physical pixels: the page's
window.scrollYbecomesydivided bywindow.devicePixelRatio. - On web this works only for a same-origin page or HTML loaded with
load_html.
Parameters:
- x (int) - The x-coordinate of the scroll position.
- y (int) - The y-coordinate of the scroll position.
Raises:
- FletUnsupportedPlatformException - If invoked on macOS.
set_javascript_modeasync
set_javascript_mode(mode: JavaScriptMode)Sets the JavaScript mode of the WebView.
- Disabling the JavaScript execution on the page may result to unexpected web page behaviour.
- Defaults to
JavaScriptMode.UNRESTRICTED, which is applied before the first page load. - On Windows, iOS, macOS and web the mode applies from the next page loaded.
Parameters:
- mode (JavaScriptMode) - The JavaScript mode to set.