question

WadghulePunam-2880 avatar image
0 Votes"
WadghulePunam-2880 asked PunamWadghule-3208 edited

Accessing host object from JS for WebView2

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?

ms-edge
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @WadghulePunam-2880 ,

Yes, you can connect the host object to window.external and get the properties of its object this way. But this approach also has some potential pitfalls, you can refer to the answer in this thread for more details.

0 Votes 0 ·

Thanks @XuDongPeng-MSFT for responding.

We are facing one more issue with WebView2.
In our bridge class, we have below method overloads,

      public string GetToken(bool isResponseToken)
 {
     if(isResponseToken)
     {
         return "Sample Response Token";
     }
     return "Sample Assertion Token";
 }
        
 public override string GetToken()
     {   
          return "GetToken for  commands"; 
     }

We are calling these methods through javascript as below,
executeJSFalse() {
this.GetTokenFalse = window.external.GetToken(false)
}
executeToken() {
this.GetToken = window.external.GetToken()
}

GetToken() method without parameter gets called properly and returns string. Method with bool parameter does not get called.
We are getting error ‘Invalid number of parameters.’ while calling method GetToken(false). It seems it tries to call GetToken() method only.
That means when we have method overloads, it does not work properly with WebView2. With IE browser it is working.
Is there any known issue for this with WebView2?

0 Votes 0 ·

0 Answers