Skip to main content

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​

PlatformWindowsmacOSLinuxiOSAndroidWeb
Supported✅✅✅✅✅✅

Usage​

Add flet-webview to your project dependencies:

uv add 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​

Source
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:

[tool.flet.android.manifest_application]
usesCleartextTraffic = "true"

Description​

Easily load webpages while allowing user interaction.

Note
  • 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 Card apply to it, but other clips, such as a Container with border_radius or a circular shape, 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 the Cross-Origin-Embedder-Policy: require-corp header 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 or None if no URL was ever loaded.
  • get_title - Get the title of the currently loaded page.
  • get_user_agent - Get the value used for the HTTP User-Agent: request header.
  • go_back - Goes back in the history of the webview, if can_go_back() is True.
  • go_forward - Goes forward in the history of the webview, if can_go_forward is True.
  • 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 = None

Defines the background color of the WebView.

Note

On macOS this colors only the area around the page, which shows when scrolling past its edges.

prevent_links: list[str] | None = None

List of url-prefixes that should not be followed/loaded/downloaded.

Note
  • On Windows, while this list is not empty, every allowed navigation is restarted as a GET request, so a form submitted with POST loses 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 = None

The URL of the web page to load.

Changing it loads the new URL. To load the same URL again, call reload or load_request.

Note

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
) = None

Fires when a log message is written to the JavaScript console.

Note
  • 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_level is always LOG.
  • On Android console.info() messages have the LOG severity level.
  • On web only messages logged after on_page_ended fired are delivered.

on_javascript_alert_dialogclass-attributeinstance-attribute​

on_javascript_alert_dialog: (
    EventHandler[WebViewJavaScriptEvent] | None
) = None

Fires when the web page attempts to display a JavaScript alert() dialog.

Note
  • 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 before on_page_ended fired still opens the browser's dialog.

on_page_endedclass-attributeinstance-attribute​

on_page_ended: ControlEventHandler[WebView] | None = None

Fires 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.

Note
  • On web this also fires when the browser refused to show the page.
  • On web with the canvaskit renderer, while on_scroll is set, this does not fire for a page from another origin or for a POST response.

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.

Note

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 = None

Fires 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.

Note

on_scrollclass-attributeinstance-attribute​

on_scroll: EventHandler[WebViewScrollEvent] | None = None

Fires when the web page's scroll position changes.

Note
  • Not supported on macOS.
  • On web it fires only for same-origin pages and HTML loaded with load_html.
  • On web with the canvaskit renderer, setting this handler keeps on_page_ended from firing for pages from another origin and for POST responses. canvaskit is the default for static web apps, and the renderer auto picks in browsers not based on Chromium.
  • On Android x and y are physical pixels: the page's window.scrollX and window.scrollY multiplied by window.devicePixelRatio.

on_url_changeclass-attributeinstance-attribute​

on_url_change: ControlEventHandler[WebView] | None = None

Fires 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.

Note

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
) = None

Fires 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.

Note
  • It also fires when url cannot 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() -> bool

Whether there's a back history item.

Note

On web the history contains only the pages the app loaded itself.

Returns:

  • bool - True if there is a back history item, False otherwise.

can_go_forwardasync​

can_go_forward() -> bool

Whether there's a forward history item.

Note

On web the history contains only the pages the app loaded itself.

Returns:

  • bool - True if there is a forward history item, False otherwise.

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
Note
  • 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:

clear_local_storageasync​

clear_local_storage()

Clears the local storage used by the WebView.

Note
  • 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:

disable_zoomasync​

disable_zoom()

Disables zooming using the on-screen zoom controls and gestures.

enable_zoomasync​

enable_zoom()

Enables zooming using the on-screen zoom controls and gestures.

get_current_urlasync​

get_current_url() -> str | None

Gets the current URL that the WebView is displaying or None if no URL was ever loaded.

Note

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 None if no URL was ever loaded.

get_titleasync​

get_title() -> str | None

Get the title of the currently loaded page.

Note

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 | None

Get the value used for the HTTP User-Agent: request header.

Note

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.

Note

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.

Note

On web the history contains only the pages the app loaded itself.

load_fileasync​

load_file(path: str)

Loads the provided local file.

Note
  • 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 with fetch() or XMLHttpRequest, or load JavaScript modules (<script type="module">).

Parameters:

  • path (str) - The absolute path to the file.

Raises:

load_htmlasync​

load_html(
    value: str, base_url: str | None = None
) -> Self

Loads the provided HTML string.

Note

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 a file:// 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 way load_file does, except on web.
  • method (RequestMethod, default: RequestMethod.GET) - The HTTP method to use. Ignored for file:// URLs.
Note
  • On Linux a POST request is sent outside the WebView and its response is then shown in it, so a failed request raises an error rather than firing on_web_resource_error.
  • On web a POST request is sent by the app itself, so the browser's cross-origin (CORS) rules apply to it.
  • On Windows a POST request fails and fires on_web_resource_error, because it is sent without a body.

reloadasync​

reload()

Reloads the current URL.

Note

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.
Note

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.

Note
  • Not supported on macOS.
  • On Android the amounts are physical pixels, so the page scrolls by y divided by window.devicePixelRatio CSS 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:

scroll_toasync​

scroll_to(x: int, y: int)

Scrolls to the provided position of webview pixels.

Note
  • Not supported on macOS.
  • On Android the position is in physical pixels: the page's window.scrollY becomes y divided by window.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:

set_javascript_modeasync​

set_javascript_mode(mode: JavaScriptMode)

Sets the JavaScript mode of the WebView.

Note
  • 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: