webview / webview

Tiny cross-platform webview library for C/C++. Uses WebKit (GTK/Cocoa) and Edge WebView2 (Windows).

Home Page:https://webview.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to run javascript code passed as an html string to the webview in secure context?

tomg7 opened this issue · comments

I am testing the webview library through webview-nodejs on Windows 11.

I would like to capture an image from the computer's webcam using the ImageCapture Web API.

Navigating to Google's image-capture example in the webview, it works fine: it prompts for camera access, it displays the webcam stream and it captures a video frame. So I assume that all the required technologies (webRTC, Permissions API, etc) are available in the webview.
I spun up a local Caddy server to run the same code locally on https://localhost and it works, too.

When I pass the same code to the webview via w.html (webview_set_html) and the code execution reaches navigator.mediaDevices.getUserMedia({ video: true }) I get a TypeError: Cannot read properties of undefined (reading 'getUserMedia') error and indeed navigator.mediaDevices is undefined.

According to MDN the MediaDevices interface is only available in secure contexts (HTTPS) and I can see that window.isSecureContext returns false in the webview.

Therefore I assume that the issue is caused by the webview running javascript code that is passed to it as an html string in an insecure context (http).

It would be nice if I did not have to run an additional web server in order to capture an image from the web camera or to use the numerous other browser features that are only available in a secure context.

Tauri for example runs the javascript code that is embedded in the Tauri app in secure context by default.

Is there a way to run javascript code passed as an html string to the webview in secure context?
An ideal solution would easily make this work through other language bindings.

After returning to this issue this morning I have a better understanding on what is going on.

The issue is certainly the lack of the secure context when the page content is set as a string using webview_set_html.

The webview_set_html method calls NavigateToString. The ICoreWebView2.NavigateToString documentation states that the origin of the new page is about:blank, but about:blank does not provide a secure context.

There is an open upstream issue to set the origin / url with NavigateToString.

Local resources provide a secure context so being able to set localhost or file as the origin of the page would solve this issue.
https is not needed. http://localhost is enough.

I am closing this issue here because it depends on an upstream feature request.