How to open an in-memory web page with WebView2?

Viewed 460

My C++ code has these steps, trying to get JavaScript-generated HTML codes.

  1. Call ICoreWebView2Settings::put_IsScriptEnabled to turn on JavaScript feature
  2. Call ICoreWebView2::NavigateToString to set an in-memory webpage.
  3. When NavigationCompleted happens, we harvest the HTML codes of the entire web page.

Unfortunately, there is apparently a race condition. Sometimes, JavaScript codes in <body> are ignored, and only the JavaScript codes in <head> have effect. Sometimes, we get <html><head></head><body></body></html>.

When using ICoreWebView2::Navigate to open a remote web page, I didn't see this problem. It seems a bug in ICoreWebView2::NavigateToString. Therefore, replacing ICoreWebView2::NavigateToString with ICoreWebView2::Navigate seems to be a better choice, but I don't know how to use ICoreWebView2::Navigate to open an in-memory HTML document. What scheme shall I use? file:// or memory://, etc.? Any suggestion? Thanks.

2 Answers

I think you can use Data URLs in ICoreWebView2::Navigate. Data URLs start with the data: scheme, you can use data:text/html, to show the HTML content. You can refer to the sample code below:

webviewWindow->Navigate(L"data:text/html,<h1>Hello, World!</h1> <script>alert('hi');</script>");

The code above will show a HTML document with "Hello, World!" and executes a JavaScript alert.

enter image description here

I've tried many ways to have JavaScript-rendered code, the best one I got is:

  1. Call ICoreWebView2::AddWebResourceRequestedFilter and ICoreWebView2::add_WebResourceRequested to enable a pseudo URI, e.g. "file://in-mem/doc".

  2. In the callback of event WebResourceRequested,

    1. Call ICoreWebView2WebResourceRequestedEventArgs::get_ResourceContext to get the request.

    2. Call ICoreWebView2Environment::CreateWebResourceResponse to create the response.

    3. Call ICoreWebView2WebResourceRequestedEventArgs::put_Response on the argument of the callback.

  3. In the callback of event NavigationCompleted, we harvest the JavaScript-rendered HTML code.

Related