Share via

Accessing host object from JS for WebView2

Wadghule, Punam 1 Reputation point
2022-02-07T13:23:11.487+00:00

In our project, we are replacing IE browser with WebView2 browser control.

For the object to javascript, we have used AddHostObjectToScript as below,
this.webView2.CoreWebView2.AddHostObjectToScript(("external", obj)

We were accessing this object through javascript in html as below,
getTokenFromJSScriptFalse() {
this.GetTokenFromJSScriptFalse = window.external.GetTokenFromJSScript(1)
}
Now for WebView2 we have to access object via,
• window.chrome.webview.hostObjects
• window.chrome.webview.hostObjects.sync

We had to make changes in javascripts to use window.chrome.webview.hostObjects. In our case for client applications it is not feasible to make changes to javascript.

Hence we are looking for way to access registered object without making changes to JS code.

We tried workaround to set window.chrome.webview.hostObjects.sync.external to window.external as below for WebView2 control,
this.webBrowser.ExecuteScriptAsync("window.external = window.chrome.webview.hostObjects.sync.external");
and it is working without making any changes to javascript.

We wanted to check with you that, can we go ahead with this approach or will it hide some of the functionalities of the windows.external object?

Microsoft Edge | Microsoft Edge development

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.