[][src]Trait webview2_sys::ICoreWebView2

pub trait ICoreWebView2: IUnknown {
    unsafe fn get_settings(
        &self,
        settings: *mut *mut *mut ICoreWebView2SettingsVTable
    ) -> HRESULT;
unsafe fn get_source(&self, uri: *mut LPWSTR) -> HRESULT;
unsafe fn navigate(&self, uri: LPCWSTR) -> HRESULT;
unsafe fn navigate_to_string(&self, html_content: LPCWSTR) -> HRESULT;
unsafe fn add_navigation_starting(
        &self,
        event_handler: *mut *mut ICoreWebView2NavigationStartingEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_navigation_starting(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_content_loading(
        &self,
        event_handler: *mut *mut ICoreWebView2ContentLoadingEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_content_loading(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_source_changed(
        &self,
        event_handler: *mut *mut ICoreWebView2SourceChangedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_source_changed(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_history_changed(
        &self,
        event_handler: *mut *mut ICoreWebView2HistoryChangedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_history_changed(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_navigation_completed(
        &self,
        event_handler: *mut *mut ICoreWebView2NavigationCompletedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_navigation_completed(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_frame_navigation_starting(
        &self,
        event_handler: *mut *mut ICoreWebView2NavigationStartingEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_frame_navigation_starting(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_frame_navigation_completed(
        &self,
        event_handler: *mut *mut ICoreWebView2NavigationCompletedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_frame_navigation_completed(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_script_dialog_opening(
        &self,
        event_handler: *mut *mut ICoreWebView2ScriptDialogOpeningEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_script_dialog_opening(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_permission_requested(
        &self,
        event_handler: *mut *mut ICoreWebView2PermissionRequestedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_permission_requested(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_process_failed(
        &self,
        event_handler: *mut *mut ICoreWebView2ProcessFailedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_process_failed(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_script_to_execute_on_document_created(
        &self,
        java_script: LPCWSTR,
        handler: *mut *mut ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandlerVTable
    ) -> HRESULT;
unsafe fn remove_script_to_execute_on_document_created(
        &self,
        id: LPCWSTR
    ) -> HRESULT;
unsafe fn execute_script(
        &self,
        java_script: LPCWSTR,
        handler: *mut *mut ICoreWebView2ExecuteScriptCompletedHandlerVTable
    ) -> HRESULT;
unsafe fn capture_preview(
        &self,
        image_format: CapturePreviewImageFormat,
        image_stream: *mut *mut IStreamVTable,
        handler: *mut *mut ICoreWebView2CapturePreviewCompletedHandlerVTable
    ) -> HRESULT;
unsafe fn reload(&self) -> HRESULT;
unsafe fn post_web_message_as_json(
        &self,
        web_message_as_json: LPCWSTR
    ) -> HRESULT;
unsafe fn post_web_message_as_string(
        &self,
        web_message_as_string: LPCWSTR
    ) -> HRESULT;
unsafe fn add_web_message_received(
        &self,
        handler: *mut *mut ICoreWebView2WebMessageReceivedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_web_message_received(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn call_dev_tools_protocol_method(
        &self,
        method_name: LPCWSTR,
        parameters_as_json: LPCWSTR,
        handler: *mut *mut ICoreWebView2CallDevToolsProtocolMethodCompletedHandlerVTable
    ) -> HRESULT;
unsafe fn get_browser_process_id(&self, value: *mut UINT32) -> HRESULT;
unsafe fn get_can_go_back(&self, can_go_back: *mut BOOL) -> HRESULT;
unsafe fn get_can_go_forward(&self, can_go_forward: *mut BOOL) -> HRESULT;
unsafe fn go_back(&self) -> HRESULT;
unsafe fn go_forward(&self) -> HRESULT;
unsafe fn get_dev_tools_protocol_event_receiver(
        &self,
        event_name: LPCWSTR,
        receiver: *mut *mut *mut ICoreWebView2DevToolsProtocolEventReceiverVTable
    ) -> HRESULT;
unsafe fn stop(&self) -> HRESULT;
unsafe fn add_new_window_requested(
        &self,
        event_handler: *mut *mut ICoreWebView2NewWindowRequestedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_new_window_requested(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_document_title_changed(
        &self,
        event_handler: *mut *mut ICoreWebView2DocumentTitleChangedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_document_title_changed(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn get_document_title(&self, title: *mut LPWSTR) -> HRESULT;
unsafe fn add_host_object_to_script(
        &self,
        name: LPCWSTR,
        object: *mut VARIANT
    ) -> HRESULT;
unsafe fn remove_host_object_from_script(&self, name: LPCWSTR) -> HRESULT;
unsafe fn open_dev_tools_window(&self) -> HRESULT;
unsafe fn add_contains_full_screen_element_changed(
        &self,
        event_handler: *mut *mut ICoreWebView2ContainsFullScreenElementChangedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_contains_full_screen_element_changed(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn get_contains_full_screen_element(
        &self,
        contains_full_screen_element: *mut BOOL
    ) -> HRESULT;
unsafe fn add_web_resource_requested(
        &self,
        event_handler: *mut *mut ICoreWebView2WebResourceRequestedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_web_resource_requested(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT;
unsafe fn add_web_resource_requested_filter(
        &self,
        uri: LPCWSTR,
        resource_context: WebResourceContext
    ) -> HRESULT;
unsafe fn remove_web_resource_requested_filter(
        &self,
        uri: LPCWSTR,
        resource_context: WebResourceContext
    ) -> HRESULT;
unsafe fn add_window_close_requested(
        &self,
        event_handler: *mut *mut ICoreWebView2WindowCloseRequestedEventHandlerVTable,
        token: *mut EventRegistrationToken
    ) -> HRESULT;
unsafe fn remove_window_close_requested(
        &self,
        token: EventRegistrationToken
    ) -> HRESULT; }

WebView2 enables you to host web content using the latest Edge web browser technology.

The normal sequence of navigation events is NavigationStarting, SourceChanged, ContentLoading and then NavigationCompleted.

\dot digraph NavigationEvents { node [fontname=Roboto, shape=rectangle] edge [fontname=Roboto]

NewDocument -> NavigationStarting; NavigationStarting -> SourceChanged -> ContentLoading [label="New Document"]; ContentLoading -> HistoryChanged; SameDocument -> SourceChanged; SourceChanged -> HistoryChanged [label="Same Document"]; HistoryChanged -> NavigationCompleted; NavigationStarting -> NavigationStarting [label="Redirect"]; NavigationStarting -> NavigationCompleted [label="Failure"]; } \enddot

Note that this is for navigation events with the same NavigationId event arg. Navigations events with different NavigationId event args may overlap. For instance, if you start a navigation wait for its NavigationStarting event and then start another navigation you'll see the NavigationStarting for the first navigate followed by the NavigationStarting of the second navigate, followed by the NavigationCompleted for the first navigation and then all the rest of the appropriate navigation events for the second navigation. In error cases there may or may not be a ContentLoading event depending on whether the navigation is continued to an error page. In case of an HTTP redirect, there will be multiple NavigationStarting events in a row, with ones following the first will have their IsRedirect flag set.

To monitor or cancel navigations inside subframes in the WebView, use FrameNavigationStarting.

Process model

WebView2 uses the same process model as the Edge web browser. There is one Edge browser process per specified user data directory in a user session that will serve any WebView2 calling process that specifies that user data directory. This means one Edge browser process may be serving multiple calling processes and one calling process may be using multiple Edge browser processes.

\dot digraph ProcessModelNClientsNServers { node [fontname=Roboto, shape=rectangle]; edge [fontname=Roboto];

Host1 [label="Calling\nprocess 1"];
Host2 [label="Calling\nprocess 2"];
Browser1 [label="Edge processes\ngroup 1"];
Browser2 [label="Edge processes\ngroup 2"];

Host1 -> Browser1;
Host1 -> Browser2;
Host2 -> Browser2;

} \enddot

Off of a browser process there will be some number of renderer processes. These are created as necessary to service potentially multiple frames in different WebViews. The number of renderer processes varies based on the site isolation browser feature and the number of distinct disconnected origins rendered in associated WebViews.

\dot digraph ProcessModelClientServer { node [fontname=Roboto, shape=rectangle]; edge [fontname=Roboto]; graph [fontname=Roboto];

Host [label="Calling process"];
subgraph cluster_0 {
    labeljust = "l";
    label = "Edge processes group";
    Browser [label="Edge browser\nprocess"];
    Render1 [label="Edge render\nprocess 1"];
    Render2 [label="Edge render\nprocess 2"];
    RenderN [label="Edge render\nprocess N"];
    GPU [label="Edge GPU\nprocess"];
}

Host -> Browser;
Browser -> Render1;
Browser -> Render2;
Browser -> RenderN;
Browser -> GPU;

} \enddot

You can react to crashes and hangs in these browser and renderer processes using the ProcessFailure event.

You can safely shutdown associated browser and renderer processes using the Close method.

Threading model

The WebView2 must be created on a UI thread. Specifically a thread with a message pump. All callbacks will occur on that thread and calls into the WebView must be done on that thread. It is not safe to use the WebView from another thread.

Callbacks including event handlers and completion handlers execute serially. That is, if you have an event handler running and begin a message loop no other event handlers or completion callbacks will begin executing reentrantly.

Security

Always check the Source property of the WebView before using ExecuteScript, PostWebMessageAsJson, PostWebMessageAsString, or any other method to send information into the WebView. The WebView may have navigated to another page via the end user interacting with the page or script in the page causing navigation. Similarly, be very careful with AddScriptToExecuteOnDocumentCreated. All future navigations will run this script and if it provides access to information intended only for a certain origin, any HTML document may have access.

When examining the result of an ExecuteScript method call, a WebMessageReceived event, always check the Source of the sender, or any other mechanism of receiving information from an HTML document in a WebView validate the URI of the HTML document is what you expect.

When constructing a message to send into a WebView, prefer using PostWebMessageAsJson and construct the JSON string parameter using a JSON library. This will avoid any potential accidents of encoding information into a JSON string or script and ensure no attacker controlled input can modify the rest of the JSON message or run arbitrary script.

String types

String out parameters are LPWSTR null terminated strings. The callee allocates the string using CoTaskMemAlloc. Ownership is transferred to the caller and it is up to the caller to free the memory using CoTaskMemFree.

String in parameters are LPCWSTR null terminated strings. The caller ensures the string is valid for the duration of the synchronous function call. If the callee needs to retain that value to some point after the function call completes, the callee must allocate its own copy of the string value.

URI and JSON parsing

Various methods provide or accept URIs and JSON as strings. Please use your own preferred library for parsing and generating these strings.

If WinRT is available for your app you can use RuntimeClass_Windows_Data_Json_JsonObject and IJsonObjectStatics to parse or produce JSON strings or RuntimeClass_Windows_Foundation_Uri and IUriRuntimeClassFactory to parse and produce URIs. Both of these work in Win32 apps.

If you use IUri and CreateUri to parse URIs you may want to use the following URI creation flags to have CreateUri behavior more closely match the URI parsing in the WebView: Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME | Uri_CREATE_NO_DECODE_EXTRA_INFO

Debugging

Open DevTools with the normal shortcuts: F12 or Ctrl+Shift+I. You can use the --auto-open-devtools-for-tabs command argument switch to have the DevTools window open immediately when first creating a WebView. See CreateCoreWebView2Controller documentation for how to provide additional command line arguments to the browser process. Check out the LoaderOverride registry key for trying out different builds of WebView2 without modifying your application in the CreateCoreWebView2Controller documentation.

Versioning

After you've used a particular version of the SDK to build your app, your app may end up running with an older or newer version of installed browser binaries. Until version 1.0.0.0 of WebView2 there may be breaking changes during updates that will prevent your SDK from working with different versions of installed browser binaries. After version 1.0.0.0 different versions of the SDK can work with different versions of the installed browser by following these best practices:

To account for breaking changes to the API be sure to check for failure when calling the DLL export CreateCoreWebView2Environment and when calling QueryInterface on any CoreWebView2 object. A return value of E_NOINTERFACE can indicate the SDK is not compatible with the Edge browser binaries.

Checking for failure from QueryInterface will also account for cases where the SDK is newer than the version of the Edge browser and your app attempts to use an interface of which the Edge browser is unaware.

When an interface is unavailable, you can consider disabling the associated feature if possible, or otherwise informing the end user they need to update their browser.

Required methods

unsafe fn get_settings(
    &self,
    settings: *mut *mut *mut ICoreWebView2SettingsVTable
) -> HRESULT

The ICoreWebView2Settings object contains various modifiable settings for the running WebView.

unsafe fn get_source(&self, uri: *mut LPWSTR) -> HRESULT

The URI of the current top level document. This value potentially changes as a part of the SourceChanged event firing for some cases such as navigating to a different site or fragment navigations. It will remain the same for other types of navigations such as page reloads or history.pushState with the same URL as the current page.

\snippet ControlComponent.cpp SourceChanged

unsafe fn navigate(&self, uri: LPCWSTR) -> HRESULT

Cause a navigation of the top level document to the specified URI. See the navigation events for more information. Note that this starts a navigation and the corresponding NavigationStarting event will fire sometime after this Navigate call completes.

\snippet ControlComponent.cpp Navigate

unsafe fn navigate_to_string(&self, html_content: LPCWSTR) -> HRESULT

Initiates a navigation to htmlContent as source HTML of a new document. The htmlContent parameter may not be larger than 2 MB of characters. The origin of the new page will be about:blank.

\snippet SettingsComponent.cpp NavigateToString

unsafe fn add_navigation_starting(
    &self,
    event_handler: *mut *mut ICoreWebView2NavigationStartingEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the NavigationStarting event. NavigationStarting fires when the WebView main frame is requesting permission to navigate to a different URI. This will fire for redirects as well.

\snippet SettingsComponent.cpp NavigationStarting

unsafe fn remove_navigation_starting(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_NavigationStarting.

unsafe fn add_content_loading(
    &self,
    event_handler: *mut *mut ICoreWebView2ContentLoadingEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the ContentLoading event. ContentLoading fires before any content is loaded, including scripts added with AddScriptToExecuteOnDocumentCreated ContentLoading will not fire if a same page navigation occurs (such as through fragment navigations or history.pushState navigations). This follows the NavigationStarting and SourceChanged events and precedes the HistoryChanged and NavigationCompleted events.

unsafe fn remove_content_loading(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_ContentLoading.

unsafe fn add_source_changed(
    &self,
    event_handler: *mut *mut ICoreWebView2SourceChangedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

SourceChanged fires when the Source property changes. SourceChanged fires for navigating to a different site or fragment navigations. It will not fires for other types of navigations such as page reloads or history.pushState with the same URL as the current page. SourceChanged fires before ContentLoading for navigation to a new document. Add an event handler for the SourceChanged event. \snippet ControlComponent.cpp SourceChanged

unsafe fn remove_source_changed(&self, token: EventRegistrationToken) -> HRESULT

Remove an event handler previously added with add_SourceChanged.

unsafe fn add_history_changed(
    &self,
    event_handler: *mut *mut ICoreWebView2HistoryChangedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

HistoryChange listen to the change of navigation history for the top level document. Use HistoryChange to check if CanGoBack/CanGoForward value has changed. HistoryChanged also fires for using GoBack/GoForward. HistoryChanged fires after SourceChanged and ContentLoading. Add an event handler for the HistoryChanged event. \snippet ControlComponent.cpp HistoryChanged

unsafe fn remove_history_changed(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_HistoryChanged.

unsafe fn add_navigation_completed(
    &self,
    event_handler: *mut *mut ICoreWebView2NavigationCompletedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the NavigationCompleted event. NavigationCompleted event fires when the WebView has completely loaded (body.onload has fired) or loading stopped with error.

\snippet ControlComponent.cpp NavigationCompleted

unsafe fn remove_navigation_completed(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_NavigationCompleted.

unsafe fn add_frame_navigation_starting(
    &self,
    event_handler: *mut *mut ICoreWebView2NavigationStartingEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the FrameNavigationStarting event. FrameNavigationStarting fires when a child frame in the WebView requesting permission to navigate to a different URI. This will fire for redirects as well.

\snippet SettingsComponent.cpp FrameNavigationStarting

unsafe fn remove_frame_navigation_starting(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_FrameNavigationStarting.

unsafe fn add_frame_navigation_completed(
    &self,
    event_handler: *mut *mut ICoreWebView2NavigationCompletedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the FrameNavigationCompleted event. FrameNavigationCompleted event fires when a child frame has completely loaded (body.onload has fired) or loading stopped with error.

\snippet ControlCompnent.cpp FrameNavigationCompleted

unsafe fn remove_frame_navigation_completed(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_FrameNavigationCompleted.

unsafe fn add_script_dialog_opening(
    &self,
    event_handler: *mut *mut ICoreWebView2ScriptDialogOpeningEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the ScriptDialogOpening event. The event fires when a JavaScript dialog (alert, confirm, or prompt) will show for the webview. This event only fires if the ICoreWebView2Settings::AreDefaultScriptDialogsEnabled property is set to false. The ScriptDialogOpening event can be used to suppress dialogs or replace default dialogs with custom dialogs.

\snippet SettingsComponent.cpp ScriptDialogOpening

unsafe fn remove_script_dialog_opening(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_ScriptDialogOpening.

unsafe fn add_permission_requested(
    &self,
    event_handler: *mut *mut ICoreWebView2PermissionRequestedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the PermissionRequested event. Fires when content in a WebView requests permission to access some privileged resources.

\snippet SettingsComponent.cpp PermissionRequested

unsafe fn remove_permission_requested(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_PermissionRequested.

unsafe fn add_process_failed(
    &self,
    event_handler: *mut *mut ICoreWebView2ProcessFailedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the ProcessFailed event. Fires when a WebView process terminated unexpectedly or become unresponsive.

\snippet ProcessComponent.cpp ProcessFailed

unsafe fn remove_process_failed(&self, token: EventRegistrationToken) -> HRESULT

Remove an event handler previously added with add_ProcessFailed.

unsafe fn add_script_to_execute_on_document_created(
    &self,
    java_script: LPCWSTR,
    handler: *mut *mut ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandlerVTable
) -> HRESULT

Add the provided JavaScript to a list of scripts that should be executed after the global object has been created, but before the HTML document has been parsed and before any other script included by the HTML document is executed. The injected script will apply to all future top level document and child frame navigations until removed with RemoveScriptToExecuteOnDocumentCreated. This is applied asynchronously and you must wait for the completion handler to run before you can be sure that the script is ready to execute on future navigations.

Note that if an HTML document has sandboxing of some kind via sandbox properties or the Content-Security-Policy HTTP header this will affect the script run here. So, for example, if the 'allow-modals' keyword is not set then calls to the alert function will be ignored.

\snippet ScriptComponent.cpp AddScriptToExecuteOnDocumentCreated

unsafe fn remove_script_to_execute_on_document_created(
    &self,
    id: LPCWSTR
) -> HRESULT

Remove the corresponding JavaScript added via AddScriptToExecuteOnDocumentCreated.

unsafe fn execute_script(
    &self,
    java_script: LPCWSTR,
    handler: *mut *mut ICoreWebView2ExecuteScriptCompletedHandlerVTable
) -> HRESULT

Execute JavaScript code from the javascript parameter in the current top level document rendered in the WebView. This will execute asynchronously and when complete, if a handler is provided in the ExecuteScriptCompletedHandler parameter, its Invoke method will be called with the result of evaluating the provided JavaScript. The result value is a JSON encoded string. If the result is undefined, contains a reference cycle, or otherwise cannot be encoded into JSON, the JSON null value will be returned as the string 'null'. Note that a function that has no explicit return value returns undefined. If the executed script throws an unhandled exception, then the result is also 'null'. This method is applied asynchronously. If the call is made while the webview is on one document, and a navigation occurs after the call is made but before the JavaScript is executed, then the script will not be executed and the handler will be called with E_FAIL for its errorCode parameter. ExecuteScript will work even if IsScriptEnabled is set to FALSE.

\snippet ScriptComponent.cpp ExecuteScript

unsafe fn capture_preview(
    &self,
    image_format: CapturePreviewImageFormat,
    image_stream: *mut *mut IStreamVTable,
    handler: *mut *mut ICoreWebView2CapturePreviewCompletedHandlerVTable
) -> HRESULT

Capture an image of what WebView is displaying. Specify the format of the image with the imageFormat parameter. The resulting image binary data is written to the provided imageStream parameter. When CapturePreview finishes writing to the stream, the Invoke method on the provided handler parameter is called.

\snippet FileComponent.cpp CapturePreview

unsafe fn reload(&self) -> HRESULT

Reload the current page. This is similar to navigating to the URI of current top level document including all navigation events firing and respecting any entries in the HTTP cache. But, the back/forward history will not be modified.

unsafe fn post_web_message_as_json(
    &self,
    web_message_as_json: LPCWSTR
) -> HRESULT

Post the specified webMessage to the top level document in this WebView. The top level document's window.chrome.webview's message event fires. JavaScript in that document may subscribe and unsubscribe to the event via the following:

   window.chrome.webview.addEventListener('message', handler)
   window.chrome.webview.removeEventListener('message', handler)

The event args is an instance of MessageEvent. The ICoreWebView2Settings::IsWebMessageEnabled setting must be true or this method will fail with E_INVALIDARG. The event arg's data property is the webMessage string parameter parsed as a JSON string into a JavaScript object. The event arg's source property is a reference to the window.chrome.webview object. See SetWebMessageReceivedEventHandler for information on sending messages from the HTML document in the webview to the host. This message is sent asynchronously. If a navigation occurs before the message is posted to the page, then the message will not be sent.

\snippet ScenarioWebMessage.cpp WebMessageReceived

unsafe fn post_web_message_as_string(
    &self,
    web_message_as_string: LPCWSTR
) -> HRESULT

This is a helper for posting a message that is a simple string rather than a JSON string representation of a JavaScript object. This behaves in exactly the same manner as PostWebMessageAsJson but the window.chrome.webview message event arg's data property will be a string with the same value as webMessageAsString. Use this instead of PostWebMessageAsJson if you want to communicate via simple strings rather than JSON objects.

unsafe fn add_web_message_received(
    &self,
    handler: *mut *mut ICoreWebView2WebMessageReceivedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

This event fires when the IsWebMessageEnabled setting is set and the top level document of the webview calls window.chrome.webview.postMessage. The postMessage function is void postMessage(object) where object is any object supported by JSON conversion.

\snippet ScenarioWebMessage.html chromeWebView

When postMessage is called, the ICoreWebView2WebMessageReceivedEventHandler set via this SetWebMessageReceivedEventHandler method will be invoked with the postMessage's object parameter converted to a JSON string.

\snippet ScenarioWebMessage.cpp WebMessageReceived

unsafe fn remove_web_message_received(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_WebMessageReceived.

unsafe fn call_dev_tools_protocol_method(
    &self,
    method_name: LPCWSTR,
    parameters_as_json: LPCWSTR,
    handler: *mut *mut ICoreWebView2CallDevToolsProtocolMethodCompletedHandlerVTable
) -> HRESULT

Call an asynchronous DevToolsProtocol method. See the DevTools Protocol Viewer for a list and description of available methods. The methodName parameter is the full name of the method in the format {domain}.{method}. The parametersAsJson parameter is a JSON formatted string containing the parameters for the corresponding method. The handler's Invoke method will be called when the method asynchronously completes. Invoke will be called with the method's return object as a JSON string.

\snippet ScriptComponent.cpp CallDevToolsProtocolMethod

unsafe fn get_browser_process_id(&self, value: *mut UINT32) -> HRESULT

The process id of the browser process that hosts the WebView.

unsafe fn get_can_go_back(&self, can_go_back: *mut BOOL) -> HRESULT

Returns true if the webview can navigate to a previous page in the navigation history. The HistoryChanged event will fire if CanGoBack changes value.

unsafe fn get_can_go_forward(&self, can_go_forward: *mut BOOL) -> HRESULT

Returns true if the webview can navigate to a next page in the navigation history. The HistoryChanged event will fire if CanGoForward changes value.

unsafe fn go_back(&self) -> HRESULT

Navigates the WebView to the previous page in the navigation history.

unsafe fn go_forward(&self) -> HRESULT

Navigates the WebView to the next page in the navigation history.

unsafe fn get_dev_tools_protocol_event_receiver(
    &self,
    event_name: LPCWSTR,
    receiver: *mut *mut *mut ICoreWebView2DevToolsProtocolEventReceiverVTable
) -> HRESULT

Get a DevTools Protocol event receiver that allows you to subscribe to a DevTools Protocol event. The eventName parameter is the full name of the event in the format {domain}.{event}. See the DevTools Protocol Viewer for a list of DevTools Protocol events description, and event args.

\snippet ScriptComponent.cpp DevToolsProtocolEventReceived

unsafe fn stop(&self) -> HRESULT

Stop all navigations and pending resource fetches. Does not stop scripts.

unsafe fn add_new_window_requested(
    &self,
    event_handler: *mut *mut ICoreWebView2NewWindowRequestedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the NewWindowRequested event. Fires when content inside the WebView requested to open a new window, such as through window.open. The app can pass a target webview that will be considered the opened window.

\snippet AppWindow.cpp NewWindowRequested

unsafe fn remove_new_window_requested(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_NewWindowRequested.

unsafe fn add_document_title_changed(
    &self,
    event_handler: *mut *mut ICoreWebView2DocumentTitleChangedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the DocumentTitleChanged event. The event fires when the DocumentTitle property of the WebView changes and may fire before or after the NavigationCompleted event.

\snippet FileComponent.cpp DocumentTitleChanged

unsafe fn remove_document_title_changed(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_DocumentTitleChanged.

unsafe fn get_document_title(&self, title: *mut LPWSTR) -> HRESULT

The title for the current top level document. If the document has no explicit title or is otherwise empty, a default that may or may not match the URI of the document will be used.

unsafe fn add_host_object_to_script(
    &self,
    name: LPCWSTR,
    object: *mut VARIANT
) -> HRESULT

Add the provided host object to script running in the WebView with the specified name. Host objects are exposed as host object proxies via window.chrome.webview.hostObjects.<name>. Host object proxies are promises and will resolve to an object representing the host object. The promise is rejected if the app has not added an object with the name. When JavaScript code access a property or method of the object, a promise is return, which will resolve to the value returned from the host for the property or method, or rejected in case of error such as there is no such property or method on the object or parameters are invalid. For example, when the application code does the following:

   VARIANT object;
   object.vt = VT_DISPATCH;
   object.pdispVal = appObject;
   webview->AddHostObjectToScript(L"host_object", &host);

JavaScript code in the WebView will be able to access appObject as following and then access attributes and methods of appObject:

   let app_object = await window.chrome.webview.hostObjects.host_object;
   let attr1 = await app_object.attr1;
   let result = await app_object.method1(parameters);

Note that while simple types, IDispatch and array are supported, generic IUnknown, VT_DECIMAL, or VT_RECORD variant is not supported. Remote JavaScript objects like callback functions are represented as an VT_DISPATCH VARIANT with the object implementing IDispatch. The JavaScript callback method may be invoked using DISPID_VALUE for the DISPID. Nested arrays are supported up to a depth of 3. Arrays of by reference types are not supported. VT_EMPTY and VT_NULL are mapped into JavaScript as null. In JavaScript null and undefined are mapped to VT_EMPTY.

Additionally, all host objects are exposed as window.chrome.webview.hostObjects.sync.<name>. Here the host objects are exposed as synchronous host object proxies. These are not promises and calls to functions or property access synchronously block running script waiting to communicate cross process for the host code to run. Accordingly this can result in reliability issues and it is recommended that you use the promise based asynchronous window.chrome.webview.hostObjects.<name> API described above.

Synchronous host object proxies and asynchronous host object proxies can both proxy the same host object. Remote changes made by one proxy will be reflected in any other proxy of that same host object whether the other proxies and synchronous or asynchronous.

While JavaScript is blocked on a synchronous call to native code, that native code is unable to call back to JavaScript. Attempts to do so will fail with HRESULT_FROM_WIN32(ERROR_POSSIBLE_DEADLOCK).

Host object proxies are JavaScript Proxy objects that intercept all property get, property set, and method invocations. Properties or methods that are a part of the Function or Object prototype are run locally. Additionally any property or method in the array chrome.webview.hostObjects.options.forceLocalProperties will also be run locally. This defaults to including optional methods that have meaning in JavaScript like toJSON and Symbol.toPrimitive. You can add more to this array as required.

There's a method chrome.webview.hostObjects.cleanupSome that will best effort garbage collect host object proxies.

Host object proxies additionally have the following methods which run locally:

  • applyHostFunction, getHostProperty, setHostProperty: Perform a method invocation, property get, or property set on the host object. You can use these to explicitly force a method or property to run remotely if there is a conflicting local method or property. For instance, proxy.toString() will run the local toString method on the proxy object. But proxy.applyHostFunction('toString') runs toString on the host proxied object instead.
  • getLocalProperty, setLocalProperty: Perform property get, or property set locally. You can use these methods to force getting or setting a property on the host object proxy itself rather than on the host object it represents. For instance, proxy.unknownProperty will get the property named unknownProperty from the host proxied object. But proxy.getLocalProperty('unknownProperty') will get the value of the property unknownProperty on the proxy object itself.
  • sync: Asynchronous host object proxies expose a sync method which returns a promise for a synchronous host object proxy for the same host object. For example, chrome.webview.hostObjects.sample.methodCall() returns an asynchronous host object proxy. You can use the sync method to obtain a synchronous host object proxy instead: const syncProxy = await chrome.webview.hostObjects.sample.methodCall().sync()
  • async: Synchronous host object proxies expose an async method which blocks and returns an asynchronous host object proxy for the same host object. For example, chrome.webview.hostObjects.sync.sample.methodCall() returns a synchronous host object proxy. Calling the async method on this blocks and then returns an asynchronous host object proxy for the same host object: const asyncProxy = chrome.webview.hostObjects.sync.sample.methodCall().async()
  • then: Asynchronous host object proxies have a then method. This allows them to be awaitable. then will return a promise that resolves with a representation of the host object. If the proxy represents a JavaScript literal then a copy of that is returned locally. If the proxy represents a function then a non-awaitable proxy is returned. If the proxy represents a JavaScript object with a mix of literal properties and function properties, then the a copy of the object is returned with some properties as host object proxies.

All other property and method invocations (other than the above Remote object proxy methods, forceLocalProperties list, and properties on Function and Object prototypes) are run remotely. Asynchronous host object proxies return a promise representing asynchronous completion of remotely invoking the method, or getting the property. The promise resolves after the remote operations complete and the promises resolve to the resulting value of the operation. Synchronous host object proxies work similarly but block JavaScript execution and wait for the remote operation to complete.

Setting a property on an asynchronous host object proxy works slightly differently. The set returns immediately and the return value is the value that will be set. This is a requirement of the JavaScript Proxy object. If you need to asynchronously wait for the property set to complete, use the setHostProperty method which returns a promise as described above. Synchronous object property set property synchronously blocks until the property is set.

For example, suppose you have a COM object with the following interface

\snippet HostObjectSample.idl AddHostObjectInterface

We can add an instance of this interface into our JavaScript with AddHostObjectToScript. In this case we name it sample:

\snippet ScenarioAddRemoteObject.cpp AddHostObjectToScript

Then in the HTML document we can use this COM object via chrome.webview.hostObjects.sample:

\snippet ScenarioAddRemoteObject.html HostObjectUsage

unsafe fn remove_host_object_from_script(&self, name: LPCWSTR) -> HRESULT

Remove the host object specified by the name so that it is no longer accessible from JavaScript code in the WebView. While new access attempts will be denied, if the object is already obtained by JavaScript code in the WebView, the JavaScript code will continue to have access to that object. Calling this method for a name that is already removed or never added will fail.

unsafe fn open_dev_tools_window(&self) -> HRESULT

Opens the DevTools window for the current document in the WebView. Does nothing if called when the DevTools window is already open

unsafe fn add_contains_full_screen_element_changed(
    &self,
    event_handler: *mut *mut ICoreWebView2ContainsFullScreenElementChangedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Notifies when the ContainsFullScreenElement property changes. This means that an HTML element inside the WebView is entering fullscreen to the size of the WebView or leaving fullscreen. This event is useful when, for example, a video element requests to go fullscreen. The listener of ContainsFullScreenElementChanged can then resize the WebView in response.

\snippet AppWindow.cpp ContainsFullScreenElementChanged

unsafe fn remove_contains_full_screen_element_changed(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with the corresponding add_ event method.

unsafe fn get_contains_full_screen_element(
    &self,
    contains_full_screen_element: *mut BOOL
) -> HRESULT

Indicates if the WebView contains a fullscreen HTML element.

unsafe fn add_web_resource_requested(
    &self,
    event_handler: *mut *mut ICoreWebView2WebResourceRequestedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the WebResourceRequested event. Fires when the WebView is performing an HTTP request to a matching URL and resource context filter that was added with AddWebResourceRequestedFilter. At least one filter must be added for the event to fire.

\snippet SettingsComponent.cpp WebResourceRequested

unsafe fn remove_web_resource_requested(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_WebResourceRequested.

unsafe fn add_web_resource_requested_filter(
    &self,
    uri: LPCWSTR,
    resource_context: WebResourceContext
) -> HRESULT

Adds a URI and resource context filter to the WebResourceRequested event. URI parameter can be a wildcard string ('': zero or more, '?': exactly one). nullptr is equivalent to L"". See COREWEBVIEW2_WEB_RESOURCE_CONTEXT enum for description of resource context filters.

unsafe fn remove_web_resource_requested_filter(
    &self,
    uri: LPCWSTR,
    resource_context: WebResourceContext
) -> HRESULT

Removes a matching WebResource filter that was previously added for the WebResourceRequested event. If the same filter was added multiple times, then it will need to be removed as many times as it was added for the removal to be effective. Returns E_INVALIDARG for a filter that was never added.

unsafe fn add_window_close_requested(
    &self,
    event_handler: *mut *mut ICoreWebView2WindowCloseRequestedEventHandlerVTable,
    token: *mut EventRegistrationToken
) -> HRESULT

Add an event handler for the WindowCloseRequested event. Fires when content inside the WebView requested to close the window, such as after window.close is called. The app should close the WebView and related app window if that makes sense to the app.

\snippet AppWindow.cpp WindowCloseRequested

unsafe fn remove_window_close_requested(
    &self,
    token: EventRegistrationToken
) -> HRESULT

Remove an event handler previously added with add_WindowCloseRequested.

Loading content...

Trait Implementations

impl ComInterface for dyn ICoreWebView2[src]

type VTable = ICoreWebView2VTable

A COM compatible V-Table

type Super = dyn IUnknown

The interface that this interface inherits from

impl<C: ICoreWebView2> ProductionComInterface<C> for dyn ICoreWebView2[src]

Implementations on Foreign Types

impl<T: ICoreWebView2 + ComInterface + ?Sized> ICoreWebView2 for ComRc<T>[src]

impl<T: ICoreWebView2 + ComInterface + ?Sized> ICoreWebView2 for ComPtr<T>[src]

Loading content...

Implementors

Loading content...