# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  VB6 WebView2-Binding (Edge-Chromium)

## Schmidt

Have just finished a Binding to the new WebView2-BrowserControl (based on Edge-Chromium).

I've included this Binding (all in a single Class, named cWebView2) in the new RC6-version of the RichClient-lib
(please download this new version 6 from its usual place, at vbRichClient.com first).

The new BaseDll-package of the RC6 now includes the official WebView2Loader.dll (version 1.0.674),
which the cWebView2-class then works against.

Please note, that the above Binding will currently require, that you install the larger:
"Evergreeen WebView2-Runtime" (not included in the RC6-BasePackage).
Here the official MS-DownloadLink for the evergreen-installer: https://go.microsoft.com/fwlink/p/?LinkId=2124703

So, after ensuring the mentioned two prerequisites:
- the Dlls of the new RC6-package in a folder of your choice + a registered RC6.dll
- and the successfull installation of the "evergreen-WebView2-runtime" via the MS-download-link above

You should now be able to test this new Edge-Browser-Binding (even on Win7-OSes) via this little VB6-Demo:
WebView2Demo.zip

Please let me know, when something is not working as expected - 
or when you want me to include a certain extra-functionality into the new cWebView2-class.

I want to "finalize" the new RC6-functionality at the end of the year (then switching Binary-Compatibility on).

Happy testing...  :Smilie: 

Olaf

----------


## xiaoyao

VERY GOOD,HOW TO get web page cookie? so i can use winhttp or xmlhttp to download URL
OR WebView2Loader.dll WILL have a method for download url,post data?

----------


## xiaoyao

CodeName=Mozilla
MinorVersion=undefined
Name=Netscape
Version=5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 Edg/86.0.622.58
CookieEnabled=true

how to test web page,its chrome or ie?
https://www.w3school.com.cn/tiy/t.asp?f=hdom_navigator

----------


## xiaoyao

HOW TO RUN JS CALL BY WEB page like :var a=btn1_click(22,33)?
i want to call vb sub from js,and back the value to js



```
    WV.AddScriptToExecuteOnDocumentCreated "function btn1_click(msg1,msg2){ vbH().RaiseMessageEvent('btn1_click',msg1+','+msg2) }"

WV.NavigateToString "<!DOCTYPE 

html><html><head><title>AppTitle</title></head><body>" & 

_
                          "<div>Hello World...</div>" & _
                          "<input id='txt1' value='foo'>" & _
                          "<button id='btn1' onclick='btn1_click(22,33)' 

>Button1</button>" & _
                      "</body></html>"
Private Sub WV_JSMessage(ByVal sMsg As String, ByVal 

sMsgContent As String, oJSONContent As cCollection)
sMsgContent=22,33
```

----------


## SearchingDataOnly

(From dm)

I tested WebView2Demo and it's great. I have some questions:

(1) Could you add IndexByItem to RC6.cCollection?

(2) Can WebView.CapturePreview capture the entire Web page, not just the visible part of the window?

(3) Could you demonstrate the drag operations of WebView, for example: Drag a button or grid from the VB6-Form to WebView, and WebView will generate a Html-Button or a Html-Table in the Web page. Similar to the following: https://www.layoutit.com/build

(4) Can V8 be integrated into RC6?

(5) If V8 is too large, can RC6 integrate a small embedded JavaScript engine similar to QuickJS or MuJS?

(6) When we use VB6 to develop commercial controls, .NET developers are not willing to use VB6 controls, they prefer to use .NET controls. When we use VB6 to develop commercial software, our commercial software can only run on the Windows platform, while our competitors' products can run on multiple platforms (Windows, Web, Android, iOS). In other words, we don't know what we can do with VB6 now? If RC6 could help developers in cross-platform, it would be a very wonderful thing.

----------


## Schmidt

> HOW TO get web page cookie?


The WebView2-interfaces do *not* include (other than the old, IE-based WebControl) 
a COM-Wrapper-ObjectModel for interaction with the DOM of a loaded document.

So, all the interaction with a currently loaded DOM has to happen via JavaScript.
That's the reason, why:
- jsProp(...)
- jsRun(...)
- jsRunAsync(...)
are included as Methods behind the WV-variable (of type cWebView2).

And in case of Cookies, that means, you will have to address them via the appropriate js-expression like this:


```
'enhance the Forms WebView-EventHandler below about an additional line, to read a given documents cookies
'when pressing the < Navigate to google.com > Button, you should see the cookies which were set from the Google-Server.
Private Sub WV_DocumentComplete()
  Debug.Print "WV_DocumentComplete"
  Debug.Print WV.jsProp("document.cookie")
End Sub
```

As for your BrowserVersion-String - the one you've posted:
_...Version=5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like  Gecko) Chrome/86.0.4240.111 Safari/537.36 Edg/86.0.622.58_
does contain a "Chromium-Version-Part" and an "Edge-Version-Part" as well... (so it's definitely not IE-based)

Olaf

----------


## Schmidt

> (1) Could you add IndexByItem to RC6.cCollection?


This is already implemented (via Optional ByRef Param: FoundItemIndex) in the cCollection.ItemExists(...) method.




> (2) Can WebView.CapturePreview capture the entire Web page, not just the visible part of the window?


One could determine (via JavaScript) the "total Height in Pixels" a Document would fit into
(whilst having a certain PixelWidth) - and then manually resize the WebView (via WV.Movexxx) temporarily,
and then call the Capture-Method.

But this feature-request came up also in the "Issue-tracker" IIRC, so I'd like to wait for the official release.




> (3) Could you demonstrate the drag operations of WebView, for example: Drag a button or grid from the VB6-Form to WebView, and WebView will generate a Html-Button or a Html-Table in the Web page. Similar to the following: https://www.layoutit.com/build


As already statet, one has to incorporate ones own js-snippets into the WebView2-Control,
to address such actions.
As e.g. shown here: https://www.w3schools.com/html/html5_draganddrop.asp




> (4) Can V8 be integrated into RC6?


With the WebView2-Binding, one already has access to the V8-js-engine (it is included via Chromium within this new Edge-based Control).




> (5) If V8 is too large, can RC6 integrate a small embedded JavaScript engine similar to QuickJS or MuJS?


I'd think that JScript9 (via cActiveScript) is already a "small and relatively fast" js-Engine one can use -
and as said, for V8-support, one can use the WebView2 (e.g. hosted-in/bound-to an invisible PicBox).




> (6) When we use VB6 to develop commercial controls, .NET developers are not willing to use VB6 controls, they prefer to use .NET controls. When we use VB6 to develop commercial software, our commercial software can only run on the Windows platform, while our competitors' products can run on multiple platforms (Windows, Web, Android, iOS). In other words, we don't know what we can do with VB6 now? If RC6 could help developers in cross-platform, it would be a very wonderful thing.


That depends on, when a VB6-compatible compiler becomes available.
My spare-time is not sufficient, to drive this side-project of mine along in a decent pace currently.

Meanwhile others might come up with "something promising" in this regard -
but the timeframe will in either case be measured in years, not months.

Olaf

----------


## LeandroA

Hi Olaf, I couldn't make it run

Err Number -2147221164   Clase no registrada

Set WV = New_c.WebView2 'create the instance

what am I doing wrong?
i think i can't register rc6.dll, but if i can load it to project

----------


## Schmidt

> what am I doing wrong?
> i think i can't register rc6.dll, but if i can load it to project


I think, that's what you need to resolve first.
Just loading the typelib of the RC6 (semiautomatically... via the VB6-IDE),
will not be enough (on a developer-machine).

You'll have to:
- keep any of the Dlls of the RC6-BasePackage-Dlls "in one place" (a single Folder you copy them to, as e.g. C:\RC6\)
- and then "deep-register" the RC6.dll there either via the included VBScript or via an *Admin*-Console calling regsvr32 behind the SysWow64 folder

HTH

Olaf

----------


## SearchingDataOnly

(From dm)




> This is already implemented (via Optional ByRef Param: FoundItemIndex) in the cCollection.ItemExists(...) method.


Yes, in many cases, cCollection.ItemExists and FoundItemIndex are more convenient. But IndexByItem is more concise and intuitive, it's very necessary to add IndexByItem to cCollection.




> I'd think that JScript9 (via cActiveScript) is already a "small and relatively fast" js-Engine one can use -
> and as said, for V8-support, one can use the WebView2 (e.g. hosted-in/bound-to an invisible PicBox).


cActiveScript does not seem to support some of the latest JS syntax and the latest RE parameters.




> That depends on, when a VB6-compatible compiler becomes available.
> My spare-time is not sufficient, to drive this side-project of mine along in a decent pace currently.


If a programming language wants to gain long-term vitality, it must have good commercial value, so as to form a stable software ecological chain around this programming language. If RC5/RC6 users can develop some valuable commercial software around RC6, then you will have more resources (funds and teams) to speed up the development of VB6-compatible compiler. I don't know if you have had such a plan.

I can develop some good commercial software with VB6 and RC5/RC6, but the problem is that if a commercial software can only run in a Windows environment, its market demand and market share will be very low. Such softwares cannot form a solid software ecological chain, nor can they provide you with more resources.




> Meanwhile others might come up with "something promising" in this regard -
> but the timeframe will in either case be measured in years, not months.


A few years is too long.
I'm thinking, if we develop a scripting language compatible with the syntax of the BASIC language, and then develop a scripting language runtime environment similar to NodeJS. Is it possible to realize a VB6-like programming language that can be cross-platform? Of course, this scripting language must have a visual IDE similar to VB6.

----------


## Arnoutdv

Check RadBasic, Mercury VB, B4X 
But this has nothing to do with this code submission

----------


## wqweto

> A few years is too long..


Like everyhting in life a new VB compiler will take enough time, patience and disposable income. Judging by the expressed lack of time *and* obvious lack of patience you must be in posession of a lot of disposable income.

Is there something that interested parties must know here?

cheers,
</wqw>

----------


## SearchingDataOnly

A small question about WebView2Demo:

After starting the computer, when opening WebView2Demo.exe or WebView2Demo.vbp for the first time, the system prompts "couldn't initialize Webview-Bingding". After closing the window and re-opening WebView2Demo.exe or WebView2Demo.vbp, the system runs normally.

In other words, every time the computer is restarted, the first initialization (WV.BindTo) always fails, and the second time is normal.

In addition, how does IE-WebBrowser achieve a function similar to WebView2.CapturePreview?

(OS: Win10)

----------


## Schmidt

> ...every time the computer is restarted, the first initialization (WV.BindTo) always fails, and the second time is normal.


The BindTo (as well as the two Navigate-Methods) have a second (optional)TimeOutSeconds-Parameter -
by default sitting at 5 seconds.

I guess your system is (shortly after booting) still quite busy with delayed loading of other base-stuff like services etc. -
in addition to loading the quite large Chromium-Runtime, ... so the default of 5sec may be a bit too short -
(I can imagine, that older magnetic disks might play a role, because I see no larger delay here on my test-OSes on SSDs).

You could:
- either try to increase that TimeOut-Param (to maybe 10sec or so)
- or set it to Zero, to tell the methods to wait for their matching EventHandlers 
.. (WV_InitComplete or WV_NavigationCompleted respectively, to proceed with your own, now async Inits from within those Handlers)




> In addition, how does IE-WebBrowser achieve a function similar to WebView2.CapturePreview?


You still planning on using the IE further???

Well, there's an IHTMLPainter interface one can cast to (IIRC, from an IHTMLWindow2), which offers a Draw-method.
There's also PrintPreview-interfaces which allow capturing of one (or more) pages.
And of course you could try to work via API-calls directly on the hWnd of that Control, to copy its current Render-Output.

Perhaps there's also some stuff hidden in all those IE-OleCmdID-EnumValues which might accomplish a Preview- or Capture-output.

Olaf

----------


## SearchingDataOnly

> The BindTo (as well as the two Navigate-Methods) have a second (optional)TimeOutSeconds-Parameter -
> by default sitting at 5 seconds.
> 
> I guess your system is (shortly after booting) still quite busy with delayed loading of other base-stuff like services etc. -
> in addition to loading the quite large Chromium-Runtime, ... so the default of 5sec may be a bit too short -
> (I can imagine, that older magnetic disks might play a role, because I see no larger delay here on my test-OSes on SSDs).
> 
> You could:
> - either try to increase that TimeOut-Param (to maybe 10sec or so)
> ...


Yes, after changing SecondsToWaitForInitComplete from 5 to 10, the problem was solved. Thank you very much.




> You still planning on using the IE further???


I plan to gradually replace IE with WebView2 in the next period of time, but it will take some time. During this period, IE and WebView2 will exist in my system at the same time.




> Well, there's an IHTMLPainter interface one can cast to (IIRC, from an IHTMLWindow2), which offers a Draw-method.
> There's also PrintPreview-interfaces which allow capturing of one (or more) pages.


Ok. I will try this method.




> And of course you could try to work via API-calls directly on the hWnd of that Control, to copy its current Render-Output.


Yes, I know this way. I can use SendMessage(...WM_PRINT...) to capture IE Preview.

In addition, my current project is almost finished. In a few months, I will start to develop a scripting language and IDE similar to VB6 (of course, the development time is also calculated in years). If you could provide some good seeds (prototypes or suggestions), maybe I can develop a decent scripting language and IDE, and this IDE may be applied to your VB6-compatible compiler.

(From dm)

----------


## Resurrected

This came as a surprise. 

Olaf, we can't thank you enough for your contribution.

I haven't tested it yet but I am already thrilled. 

This is something I have been searching for for a long time.

----------


## saturnian

Hello Olaf
Fantastic job! I dreamed about it for many months and you did it, fabulous!


Is there a way to force the localization of the cWebView2 component? On my computer, the sub menus are still in English despite an installation on a French Windows 10!


The only way I have found to solve this problem is to destroy the EN-US.pak file in the Locales folder of the EdgeWebView installation and rename fr.pak to EN-US.pak! It works but it is not very clean!


Do you have an idea ?


Many Thanks

----------


## Schmidt

> Is there a way to force the localization of the cWebView2 component? 
> On my computer, the sub menus are still in English despite an installation on a French Windows 10!


Ah, yes... sorry.

Forgot to reset my internal Lang-Handling "to normal" (it was still hardwired to "en" for my own tests) ...
(fixed that just now, so the next RC6-version will start with the default-language of the current system again, regarding Popup-Menus and other localizations).

But (regarding a workaround, applied to the version you currently have...) - 
there's always the last (optional) Param in the BindTo-method, which can "influence everything" (config-wise).

BackGround:
This last param (additionalBrowserArguments) can take up (and later represents) the commandline-args,
which are passed to the Chromium-Process which gets started under the covers for every WebView.

So, a simple change of the BindTo-line (passing an appropriate cmd-string):
If WV.BindTo(picWV.hWnd, , , , "--lang=fr") = 0 Then ...
or (for the chinese readers here, because it might not be obvious)
If WV.BindTo(picWV.hWnd, , , , "--lang=zh-cn") = 0 Then ...
...should do it for you (until the next RC6-version, where - as said - the current locale will determine the default again).

As for the list of available commandline-switches - it is quite a long one (but described for example here):
https://peter.sh/experiments/chromiu...line-switches/

HTH

Olaf

----------


## saturnian

thank you so much, Olaf

----------


## saturnian

Another question, Olaf! 
Is there a way to intercept the URL when opening a new window after clicking on the "Open in new tab" submenu? 
This would allow programming the display of the new page in a new cWebView2

----------


## carl039

Thanks Olaf, this is really superb work.  My VB6 app can finally be HTML5 compatible.  :Smilie:

----------


## Schmidt

> Another question, Olaf! 
> Is there a way to intercept the URL when opening a new window after clicking on the "Open in new tab" submenu? 
> This would allow programming the display of the new page in a new cWebView2


Right, the old Param-amount in that Event was only allowing "suppression of the built-in NewWindow-Handling"
(though did not give much info about "what to construct, in case one wants to create his own thing").

So, this Event was enhanced in the new version 6.0.2, which I've just uploaded to the usual place...

A Test-Handler for the original demo (showing the new incoming Event-Args) is the following one:


```
Private Sub WV_NewWindowRequested(ByVal IsUserInitiated As Long, IsHandled As Long, ByVal URI As String, NewWindowFeatures As RC6.cCollection)
  Debug.Print "URI: "; URI
  
  Dim i As Long 'Print out, what's sitting behind the NewWindowFeatures JSON-Collection
  For i = 0 To NewWindowFeatures.Count - 1
    Debug.Print NewWindowFeatures.KeyByIndex(i), NewWindowFeatures.ItemByIndex(i)
  Next
  
  IsHandled = 1 'prevent the WebView from "doing its own thing" about the new window
End Sub
```

HTH

Olaf

----------


## saturnian

Thanks, Olaf! It works perfectly

----------


## xiaoyao

can you make a dll only support cWebView2?(Like 100kb?)
how to call WebView2Loader.dll without rc6.dll?
RC6.dll is too larger ,4MB.

----------


## xiaoyao

V8Engine.dll 1.34M, BY 2018
stdcall OR CDECL,Quickjs also is good for test

can test fastdb.dll for vb6?
a memory db lib

----------


## saturnian

Hello Olaf
If I am using WebView2-BrowserControl on an MDIChild window, I have some issues.
For example, the DocumentComplete event is not fired and the component is very slow
What is the problem ? Do you have an idea ?

François

----------


## Schmidt

> ... can you make a dll only support cWebView2?(Like 100kb?)


I could, but I won't... 
It doesn't make much sense to save 1 or 2 MB in deployment-size, when "the other needed part" -
(the "evergreen WebView-runtime" from MS) is about 50MB already.




> ... how to call WebView2Loader.dll without rc6.dll?


Basically by writing your own binding:
- first, by reworking the SDKs WebView2.*tlb* (making its COM-interfaces more "VB-friendly")
- and then writing your own wrapper-class against the interfaces of this typelib (without exposing the typelib-types on the VB6-Class-interface)
- the finally resulting VB6-Class then usually placed within your own VB6-AX-Dll, to avoid separate delivery of the WebView2.*tlb* 




> RC6.dll is too large ... 4MB.


The current deployment-size of the RC6 is about**:
- 3.4MB (in a *.zip archive ... with current inet-speeds, downloadable in about 0.3 seconds)
- 2.5MB (in a *.7z archive ... with current inet-speeds, downloadable in about 0.2 seconds)

And that makes it the smallest "DB- and GUI-including" Desktop-App-Framework on the planet ...
(it is significantly smaller than e.g. GTK3, QT, Electron or "Avalonia+.NET-Core5")

For most "non Hello-World-Apps" (which do something useful), you will have to deploy "a set of Dlls/OCXes alongside your Exe" anyways.

So, when you develop and later deploy your App based on a dozen of smaller libs (Dlls and OCXes) - this will sum up to typically:
- about 2-4MB in your deployment-zip (or perhaps 5-8MB, when you include Icon+ Image-Resources and maybe a Font or two). 

So no, I cannot see where the big "burden" from introducing the RC6 will come in 
(which would allow you, to replace most of your other COM-dependencies with a single one in your App).

Olaf

----------


## Schmidt

> Hello Olaf
> If I am using WebView2-BrowserControl on an MDIChild window, I have some issues.
> For example, the DocumentComplete event is not fired and the component is very slow
> What is the problem ? Do you have an idea ?


What OS is that scenario running on?
And could you post a little "mockup.zip" which includes the basic-setup (with the MDI-ChildWindows and the Bindings on them) -
and which would allow me to reproduce what you've seen?

Another related question would be...
If you change from "MDIChildWindow-hosting" to "normal Forms + PictureBoxes" (maybe behind a "tabbed interface") -
do you see differences in behaviour (when running against the same http-server, using the same HTML5-inputs)?

If yes, then it might be something related to the VB6 MDIChildWindow-class (and its slightly "off-standard" message-pumping/handling underneath)...

Olaf

----------


## Schmidt

> V8Engine.dll 1.34M, BY 2018
> stdcall OR CDECL,Quickjs also is good for test


As already stated in my reply to dreammanor (dm) here:
You can already make use of "V8" via the WebView2-Binding 
(which will then include a proper "window-object" for your V8-scripts already).




> can test fastdb.dll for vb6?
> a memory db lib


I've already done such a test-comparison (in a former reply to you).
And the result was, that the RC5/RC6-wrapper for SQLite performs better than "fastdb".

In-Memory-DB scenarios are possible via SQLite as well:
- either via the "normal" cConnection-SQLite-wrapper Class in "::memory::"-Mode
- or via the cMemDB-class (which offers a few more convenience-functions on top of cConnection)

Olaf

----------


## saturnian

I found !
I have misused the properties of cWebview!


'WV.AreDefaultContextMenusEnabled = True
'WV.AreDefaultScriptDialogsEnabled = True
'WV.AreDevToolsEnabled = True
'WV.AreHostObjectsAllowed = True
'WV.IsScriptEnabled = True
'WV.IsWebMessageEnabled = True

 WV.IsStatusBarEnabled = True


If I uncomment this whole block of code, it doesn't work! Otherwise everything works fine (just with  WV.IsStatusBarEnabled = True )

----------


## Schmidt

> I found !
> I have misused the properties of cWebview!
> 
> 
> 'WV.AreDefaultContextMenusEnabled = True
> 'WV.AreDefaultScriptDialogsEnabled = True
> 'WV.AreDevToolsEnabled = True
> 'WV.AreHostObjectsAllowed = True
> 'WV.IsScriptEnabled = True
> ...


That's a bit surprising, because all of these Props are (by default, after initialization) already "On" (at C++ Boolean-Value = 1).

What you should keep in mind though is, that I've implemented these Boolean-Props "As Long" 
(to directly map between the C++ Boolean prop-calls and the Wrapper-Props).

So, what gets passed along (into the C++ iplementation of the WebView) in your example above,
are (due to VBs automatic Type-coercing) "Long-Values which are -1" (coerced from VB6-True).

So these "-1" Values you pass (in a 32Bit-slot, having all bits at 1) might confuse the C++-code (although, normally this should not be an issue).

That said, ... testing.... and arrrghhh... 
Whilst checking this in the little Demo-App of the opener thread (placing your calls after the BindCall),
you are right indeed - the True Values (transported as -1 Longs) confuse the WebView2 here as well... (every Prop-setting-line being active)

But good news... I have no issues when changing "all the True's" to the C++ Value 1:


```
Private Sub Form_Load()
  ...

  If WV.BindTo(picWV.hWnd) = 0 Then MsgBox "couldn't initialize WebView-Binding": Exit Sub
  Debug.Print WV.GetMostRecentInstallPath
 
  WV.AreDefaultContextMenusEnabled = 1
  WV.AreDefaultScriptDialogsEnabled = 1
  WV.AreDevToolsEnabled = 1
  WV.AreHostObjectsAllowed = 1
  WV.IsScriptEnabled = 1
  WV.IsWebMessageEnabled = 1
  WV.IsStatusBarEnabled = 1

  LocalWebViewInit 'initialize the WebView for local usage here in our Form
End Sub
```

Ok then, please expect the next RC6 version to have proper VB6-Boolean types on all the relevant Config-Props.
(which I will then take care of internally, mapping them to the correct C++ Boolean-Type).

So, thanks for your testing, which made this behaviour apparent in this still "early stage" 
(where the RC6-interfaces for its new Class-Additions are not yet "finalized").

Olaf

----------


## xiaoyao

by vfb maybe no need rc6.dll,WebView2Loader.dll
it'S  like vc++

----------


## saturnian

> So, thanks for your testing, which made this behaviour apparent in this still "early stage" 
> (where the RC6-interfaces for its new Class-Additions are not yet "finalized").
> 
> Olaf


This is nothing compared to the fabulous work you do for the community !
Thanks again, Olaf


To test, I wrote a multi-tab browser, which begins to work well.
I realized that it was necessary to avoid giving the focus to another control, in the NavigationCompleted event. If you want to modify a display based on an error number, for example, it is better to do so by activating a timer which will trigger the display late.

Other thing : the URLs "chrome://flags", "chrome://history", "chrome://downloads",...  work but do not trigger the DocumentComplete event, which sometimes causes the Webview component to lag for several tens of seconds! I don't know why !

Sincerely

François

----------


## Schmidt

> Other thing : the URLs "chrome://flags", "chrome://history", "chrome://downloads",...  work but do not trigger the DocumentComplete event, which sometimes causes the Webview component to lag for several tens of seconds! I don't know why !


Perhaps these "internal URLs" do not really "manifest" themselves in a true document...
Did you try to use the NavigationCompleted-event for these URLs instead?

Olaf

----------


## SearchingDataOnly

(From dm)

I've bound WebView to cwMyWidget and it works very well. Now I have two questions:
(1) How to add my own right-click menu to WebView?
(2) Is it possible to bind IE-WebBrowser-Control (Shell.Explorer.2) to cWidgetBase or cWidgetRoot? If this is possible, I can keep both WebView2 and IE-WebBrowser in my system. Thanks.

*Edit:*
The first question has been solved:
Step1: WV.AreDefaultContextMenuEnabled = False
Step2: WV_UserContextMenu Event

----------


## SearchingDataOnly

The third question:
(3) When using WV.Navigate to open an html file, everything is OK. The external css files and js files in the html file can be accessed normally. However, when using WV.NavigateToString to open an html-string, the external css files or js files contained in the html-string will not be accessible, and DevTools prompts "Not allowed to load local resource...".

I'd like to know if there is a way to solve this problem (for example, can this problem be solved by cWebServer?). In my software, all Html operations are done through html-strings instead of html-files. In other words, I need to use WV.NavigateToString a lot instead of WV.Navigate a file. (Note: There is no such problem in IE-WebBrowser)

In addition, after I used the parameter "--disable-web-security --allow-file-access-from-files --allow-file-access", DevTools prompts "Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME"


*Edit:*
The problem discussed in the following thread is similar to mine:
https://github.com/MicrosoftEdge/Web...ack/issues/642

The poster seems to have solved the problem through SetVirtualHostNameToFolderMapping, but I have not seen the SetVirtualHostNameToFolderMapping API in RC6.WebView.

*Edit 2:*
Two other links related to this issue:

API Spec for NavigateWithWebResourceRequest
https://github.com/MicrosoftEdge/Web...9267942e836977

WebView.NavigateToLocalStreamUri(Uri, IUriToStreamResolver) Method
https://docs.microsoft.com/en-us/uwp...treamResolver_

----------


## saturnian

> Did you try to use the NavigationCompleted-event for these URLs instead?
> 
> Olaf


Hello Olaf


I, of course, tried to use the NavigationCompleted event. But trying to give focus to another object  in this event freezes the cWebView component for several minutes, often. I solved this by activating a timer in the NavigationCompleted event which itself, a second after, update the other objects (The form caption with the tltle of the web page, for example)

----------


## saturnian

Olaf


is it possible to expose the "NavigationStarting" event in cWebView2? It seems to me that this is the only event in Microsoft's WebView2 control that is not present in cwebView2!

Kindly
François

----------


## SearchingDataOnly

The fourth question:
(4) I need to place multiple WebViews on my Form or WidgetForm. I bind a WebView to a cwWidget through "WV.BindTo(W.Root.hWnd, 10)". 
The question is, when this cwWidget is removed, how to remove the bound WebView at the same time?

----------


## Thierry76

Thanks a lot Olaf ! 
I try a little your code last sunday and it's work well ....
I have one question, did somebody find a way to install an Edge extension by code on the WebView2 ? Is it possible ? I beggin in this sort of developement  so excuse me if my question is stupid...

_PS I dream of your webviev2 with diagrams.net (drawio-desktop)...._

----------


## Schmidt

> _PS I dream of your webviev2 with diagrams.net (drawio-desktop)....
> _


Why not just load a js-based charting-lib into the WebView (instead of a plugin)? 

There's a dozen or more quite good ones out there -
the one we've decided to use is dc.js (because it's open - and based on the svg+canvas-lib d3.js, which we had in use already):

Here's a quite impressive example (which supports zooming and range-shifting on an interdependent, complex dataset):
https://dc-js.github.io/dc.js/ 

And here a turorial for it (normally, you'll only need a dozen of js-config-lines, to visualize a certain chart-type).
https://www.tutorialspoint.com/dcjs/index.htm

If you're more interested in org- and flow-charts... simple ones can be created directly in code via d3.js -
but there's also libs out there which specialize in that kind of thing ...
(though I have not needed any org- and flowchart functionality so far, so cannot give any useful hints).

Olaf

----------


## xiaoyao

> @xiaoyao: Does VFB have bindings for the WebView2 built-in?
> 
> What's the point spamming every thread with links to it?
> 
> @admins: Do cleanup my reply too, please.
> 
> cheers,
> </wqw>


YES VFB WITH MINIBLINK webbrowser,chrome core ,node.dll

----------


## xiaoyao

> I could, but I won't... 
> It doesn't make much sense to save 1 or 2 MB in deployment-size, when "the other needed part" -
> (the "evergreen WebView-runtime" from MS) is about 50MB already.
> 
> 
> Basically by writing your own binding:
> - first, by reworking the SDKs WebView2.*tlb* (making its COM-interfaces more "VB-friendly")
> - and then writing your own wrapper-class against the interfaces of this typelib (without exposing the typelib-types on the VB6-Class-interface)
> - the finally resulting VB6-Class then usually placed within your own VB6-AX-Dll, to avoid separate delivery of the WebView2.*tlb* 
> ...


more times,i no need rc6.dll.
but i need Chromium or edge ,or miniblink (by Chromium),so if only one dll vbedgeCom.dll or stdcall_edge.dll,
i think it's best
if it's make ocx control,i think it's easy for vb user,excel vba userform
if it's support x64 like a stdcall dll,it's also can use in vfb ide FOR X64 EXE (VISUAL freebasic)

----------


## Schmidt

> ...more times,i no need rc6.dll.


Then this thread is not for suitable for you.
<shrug/>

What's discussed here, is a Binding to the *EverGreen*-Runtime of the MS-Edge-Chromium-WebControl.

EverGreen meaning, that this Runtime has to be installed *only once* on a given Client-Machine.
After that, the regular Windows-Edge-Updates will update also this WebControls Chromium-Runtime without any further User-intervention.

So, the Client-Machine is guaranteed, to always use a WebView-Control with the latest Security- and Bug-Fixes.

This is not the case for e.g. "miniblink" - which (have just checked in their Repo) is already 2 years out of date.

Olaf

----------


## rameshpatel9

Hi Olaf,

Is there a way to implement late-binding for WebView2? This is to handle a scenario where user has not yet installed pre-requisites (WebView2 Runtime and RC6).

----------


## Schmidt

> Is there a way to implement late-binding for WebView2? 
> This is to handle a scenario where user has not yet installed pre-requisites (WebView2 Runtime and RC6).


To make use of the WebView2-EdgeChromium-BrowserControl, 
you have to "bind it to a normal hWnd" (in the Demo, this is provided by a VB6.PictureBox).

And that Binding is initiated via an RC6-Class (cWebView).

So, the RC6 is a pre-requisite to make all that work.

Not sure, what you mean with "late-binding" - but in case you mean "without running a prior setup, or ensuring registry-entries" - 
that's possible when you:
- ship the 5 RC6-Dlls in a \Bin\ Subfolder of your deployment-zip
- then instantiate New_c regfree within your App (via a declared DirectCOM.dll GetInstance or GetInstanceEx-call)
- and then initiate the Binding by a Class-instance, derived via New_c.WebView

The only other pre-requisite is, that the Users have installed the "EverGreen-runtime" from the MS-link I gave in the First posting here.

HTH

Olaf

----------


## oskarrr

Hello!

I am using WebView2 during 6 months. It was working perfectly.

But now, stop work without reason!

The strange thing is that: From compiler VB6 it works perfectly.
But if I generate .exe file, don´t work: "Can not initialize webview2"

I can not find where is the problem.
Any idea?

I reinstall component, register dll again...

Thank you!

----------


## jpbro

Unfortunately, it looks like MS might have broken something: https://www.vbforums.com/showthread....n-compiled-exe.

----------


## oskarrr

> Unfortunately, it looks like MS might have broken something: https://www.vbforums.com/showthread....n-compiled-exe.


wow, I was getting crazy. Fortunatly, I have followed the instructions of "saturnian" and now works perfectly.

Thank you so much!

----------


## WZabel

First of all, many thanks to Olaf for this great work.

Meanwhile a newer version od WebView2 has been released, 89.0.774.50 is working with IDE and compiled programs.

To avoid such problems in future i tried to use a fixed version, with no success.  :Frown: 



```
BindTo(HosthWnd As Long, [SecondsToWaitForInitComplete As Double = 8], [browserInstallPath As String], [userDataFolder As String], [additionalBrowserArguments As String]) As Long
```

is not binding when setting the second argument. 

Has anyone tested this before?

Robert

----------


## xiaoyao

how to call by vc++ for show edge like a ocx on wpf(window,or put to hwnd)

I want call by vfb(visual freebasic ide),I don't want use ocx or com dll

----------


## Schmidt

> Meanwhile a newer version od WebView2 has been released, 89.0.774.50 is working with IDE and compiled programs.


Yep, I've described that here: https://www.vbforums.com/showthread....=1#post5513856




> To avoid such problems in future i tried to use a fixed version, with no success.


I've made a few comments about that in the above link as well...




> ```
> BindTo(HosthWnd As Long, [SecondsToWaitForInitComplete As Double = 8], [browserInstallPath As String], [userDataFolder As String], [additionalBrowserArguments As String]) As Long
> ```
> 
> is not binding when setting the second argument.


The second argument is the timeout you plan to wait for the Init-Process to finish...

If you want to set the EdgeInstall-Path, this has to be done in the 3rd-Parameter.

Here is an example, how I was able to load directly from a fixed version (in my App.Path):


```
Private Sub Form_Load()
  Visible = True '<- it's important, that the hosting TopLevel-Form is visible...
 
  Set WV = New_c.WebView2 'create the instance
  
  Dim P As String
'      P = WV.GetMostRecentInstallPath() '<- this is what I use underneath the BindTo-call, when you don't give a specific path
      P = App.Path & "\Microsoft.WebView2.FixedVersionRuntime.89.0.774.50.x86"
  Debug.Print P
  
  If WV.BindTo(picWV.hWnd, 5, P, App.Path) = 0 Then MsgBox "couldn't initialize WebView-Binding": Exit Sub
'  If WV.BindTo(picWV.hWnd) = 0 Then MsgBox "couldn't initialize WebView-Binding": Exit Sub

  '...
```

HTH

Olaf

----------


## Schmidt

> ... I don't want use ocx or com dll


Then you are out of luck - because the WebView2Loader.dll from MS *is* a COM-dll.
(providing it's COM-Objects over "flat-API-entry-call" - and later on "building on that" via a matching typelib)

And as always, your postings do not make much sense 
(WPF belongs to the .NET-universe - and VFB is "Class-less, COM-less" flat-APIs only)

The only IDE which can "talk" to the WebView2Loader-Objects directly 
(without any "extra-marshalling" or "COM-call-support-modules"), is the VB6-IDE.

And we are here in a Sub-Forum where VB6 is discussed...
Please stop spamming this Forum with your nonsense.

Olaf

----------


## xiaoyao

> @xiaoyao: Does VFB have bindings for the WebView2 built-in?
> 
> What's the point spamming every thread with links to it?
> 
> cheers,
> </wqw>


I didn't fully express my problem. I'm sorry.
vfb support miniblink,chrome core only one DLL.
edge like google beowser.For example, running speed and Lesser memory, there are many advantages.
So I would like to ask VfB how to call the edge, the main support for com is not perfect, so  is there anyway only a DLL can be called?(without rc6.dll)

Previously, VfB did not support the creation of com DLLs, but now it can create the built-in TLB information. You know a lot about com OCX. It would be more convenient if you could increase the build to OCX.

----------


## Schmidt

> vfb support miniblink,chrome core only one DLL.
> ... running speed and Lesser memory, there are many advantages.


That is not true, because in the end there's always separate Chromium-Processes which will be spawned.
(and those ChildProcesses will have the basically same performance and mem-consumption).




> So I would like to ask VfB how to call the edge...


You contradict yourself.

Why would you now suddenly need an Edge-Binding for FreeBasic, when "miniblink" is so much better (in your opinion).

But as already said, stop spamming these threads with unrelated things like FreeBasic
(I consider FB a great tool - but it has no place in this VB6-related Forum-Thread).




> You know a lot about com OCX. 
> It would be more convenient if you could increase the build to OCX.


I don't really know, what exactly you are talking about here - but for your information,
a COM-library which exists as a Dll, is far more versatile (and much easier to use) -
 compared to a COM-lib which offers "visual COM-Objects" behind an OCX-incarnation.

That's with regard to "instancing"...
A "normal COM-Object-instance" is much easier to load from a COM-Dll,
compared to the quite messed up "siting-processes" which are needed in case of a "visual COMObj-instance from an OCX".

Olaf

----------


## xiaoyao

vb6 Slowly be eliminated,so I study vfb,it'S like vc++.
Microsoft. Net framework, but also weakened the COM, OCX control package.So I want to ask if there is a way to call edge by Stdcall?


WebView2Loader.dll ,why Double-clicking will not prompt you that you have successfully registered.

The main reason is that some computer permissions are not enough and do not support the registration com DLL.

You may be able to call com objects using just the windows API. So I want to learn how to create a simple WebView 2 page,How many windows APIs do you need to call ,for load webview2?
If rc6. Dll exports a stdcall apiThat would be too convenient.
dim web as long
web =loadWebviewTo(picture1.hwnd) 
webviewOpenUrl(web,"http://*")

In fact, There is an open source browser miniblink" like a activex control OCX ( chromium,only need one dll) is using this principle to operate the Google Chrome Kernel,This is a reduced version of the feature, and the version is relatively old.
edge with chromium ,The function is relatively complete,It's better than the miniblink. "A lot more powerful.".

----------


## byomi1

Hi Olaf,

a shameless semi-offtopic question related VBA / MSAccess:

Any chance I can get Webview2 working in MS Access / VBA???

Greets from Germany

----------


## xiaoyao

> Hi Olaf,
> 
> a shameless semi-offtopic question related VBA / MSAccess:
> 
> Any chance I can get Webview2 working in MS Access / VBA???
> 
> Greets from Germany


Edge-Binding,Microsoft's new version of WIN10 may have a built-in Google kernel EDGE browser. In addition, the COM interface provided by Microsoft has been generally used for several years and is relatively stable and perfect.
You can also use VB6 to develop an OCX control （put WebView2-Binding on usercontrol）, and then load the user-defined control to the EXCEL, ACCESS VBA form

----------


## SteveMB

Hi,

I've been trying to get the demo from the first post to run. I've downloaded the latest RC6 version from RichClient-lib (Version 6.0.8) and the evergreen webview2 runtime installer from the given microsoft link. The webview2 runtime installed successfully, as did RC6 (using the VBscripts in the zip package). As recommended, all of the dlls are in the same folder.

When I try to compile the WebView2Demo, I'm getting the following error message when it reaches the event handlers (with parameters) in fMain.frm 

_Compile error: Procedure declaration does not match description of event or procedure having the same name_

Is this demo now obsolete (and is there a newer version somewhere)? Or have Microsoft changed things again and broken this functionality completely?

----------


## jpbro

> When I try to compile the WebView2Demo, I'm getting the following error message when it reaches the event handlers (with parameters) in fMain.frm 
> 
> _Compile error: Procedure declaration does not match description of event or procedure having the same name_


It looks like some of the RC6 cWebView2 procedure declarations have changed. If you modify the declarations for the following 2 events, it should work:



```
Private Sub WV_AcceleratorKeyPressed(ByVal KeyState As eWebView2AccKeyState, ByVal IsExtendedKey As Boolean, ByVal WasKeyDown As Boolean, ByVal IsKeyReleased As Boolean, ByVal IsMenuKeyDown As Boolean, ByVal RepeatCount As Long, ByVal ScanCode As Long, IsHandled As Boolean)

Private Sub WV_NavigationCompleted(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long)
```


Some "Longs" were changed to be more sensible "Booleans".

----------


## SteveMB

> It looks like some of the RC6 cWebView2 procedure declarations have changed. If you modify the declarations for the following 2 events, it should work:
> 
> 
> 
> ```
> Private Sub WV_AcceleratorKeyPressed(ByVal KeyState As eWebView2AccKeyState, ByVal IsExtendedKey As Boolean, ByVal WasKeyDown As Boolean, ByVal IsKeyReleased As Boolean, ByVal IsMenuKeyDown As Boolean, ByVal RepeatCount As Long, ByVal ScanCode As Long, IsHandled As Boolean)
> 
> Private Sub WV_NavigationCompleted(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long)
> ```
> ...


Thanks jpbro, nice to see it was something relatively simple to fix. I've got the demo compiling and running now. Now I'll have to work out how best to build it into my application and see how it runs there.

----------


## SearchingDataOnly

> Thanks jpbro, nice to see it was something relatively simple to fix. I've got the demo compiling and running now. Now I'll have to work out how best to build it into my application and see how it runs there.


Maybe the following example is useful to you:
https://www.vbforums.com/showthread....-WebView2-Demo

----------


## jackr

Hi Olaf,

I'm trying to install Webview2Demo.  I followed the instructions but I get the error:"Procedure declaration does not match description of event or procedure having the same name".  Any ideas why.  Thank you very much!

-Jack

----------


## jackr

one question:

 using the example and navigating to "google.com",  I can't seem to be able to get the "document.getElementById('btn1').innerHTML" working using WV.jsProp.  Any ideas? basically, I need the html of the entire page I just navigated to.  I assume I can do so using "body.innerHTML"

----------


## SearchingDataOnly

> Hi Olaf,
> 
> I'm trying to install Webview2Demo.  I followed the instructions but I get the error:"Procedure declaration does not match description of event or procedure having the same name".  Any ideas why.  Thank you very much!
> 
> -Jack


The answer you want is in post#62

----------


## jackr

> The answer you want is in post#62


thanks  that works!

----------


## jackr

Is there a way to invoke a js click such as
 WV.jsRun("document.getElementById('Somebutton')".click()")
I was unable to invoke a click with that 

thanks for your help!

----------


## Schmidt

> Is there a way to invoke a js click such as
>  WV.jsRun("document.getElementById('Somebutton')".click()")


WV.jsRun is thought for simple (for the most part, self-defined) functions...

For more complex "actions" like yours above, try it with:
WV.ExecuteScript "document.getElementById('Somebutton').click()"
instead.

HTH

Olaf

----------


## jackr

That helps, thanks again!!

----------


## xiaoyao

what's MicrosoftEdgeWebView2Runtime?
Is the development version of the interface open?

How to operate the EDGE that is installed or that comes with WIN10, can I control the CHROME kernel without installing any RUNTIME? Maybe only Google Control Protocol, based on HTTP port, like WEBDRIVER?

----------


## xiaoyao

The CHROME kernel environment, there are three ways to get:

Install the EDGE (Chromium) of the development version, the stable version of the EDGE does not currently support WebView2 controls.
Install independent WebView2 Runtime, which can download and upgrade an EDGE Chromium kernel separately
Embedding Edge Chromium kernel

I don't know if there's a way. Do not need to install, only need to extract the file, and Have the least hard disk space

----------


## xiaoyao

Edge Webview2 Automatic installation, detect the installed version-VBForums
https://www.vbforums.com/showthread....talled-version

How to use code-behind automatic installation MicrosoftEdgeWebView2RuntimeInstallerX86？

https://msedge.sf.dl.delivery.mp.mic...stallerX86.exe

Which URL can use the code to automatically download the latest version? Plus automatic installation is very convenient

【install used 32 seconds, occupying 444mb of hard disk space】
use miniblink.DLL or cef.DLL(10-50MB)

For the chromium kernel, only one DLL is needed. Use this mini-small WEBKIT-related kernel as much as possible. If some web pages are too complicated and require the latest HTML5 technology to display, then use Microsoft's EDGE runtime library. 450Mb is more than 10-50mb, which takes up too much hard disk space.

----------


## xiaoyao

```
Function CheckSetupOk() As Boolean
    'It takes 10 seconds to check whether the edge runtime component is installed successfully. Is there a faster method?
    Dim WV As cWebView2
    Set WV = New_c.WebView2
    CheckSetupOk = WV.BindTo(Me.hWnd) <> 0
    Set WV = Nothing
End Function

Function DonwSetupTool() As Boolean
Dim URL As String
URL = "https://go.microsoft.com/fwlink/p/?LinkId=2124703"
'xmlhttp download***
'save as :Edge_Webview2RunTime.exe

Dim Size1 As Long
Size1 = FileLen(App.Path & "\Edge_Webview2RunTime.exe")
DonwSetupTool = Size1 > 1024 ^ 2

end function
```

install used 32 seconds, occupying 444mb of hard disk space
I dont know if there is a silent installation parameter to prevent him from displaying the download and installation interface

*MicrosoftEdgeWebview2Setup.exe /silent /install* 

check Registry information：
Microsoft Edge WebView2 Runtim(92.0.902.8)
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}
get string value(PV and name)

----------


## softv

> I could, but I won't... 
> It doesn't make much sense to save 1 or 2 MB in deployment-size, when "the other needed part" -
> (the "evergreen WebView-runtime" from MS) is about 50MB already.
> ... .. .
> Olaf


Is there a necessity that the end-user systems (where my application is installed) also should have "evergreen WebView-runtime" installed in them (if not already installed)? 

Kind regards.

----------


## xiaoyao

You can keep it updated automatically. It's also very convenient. Ie is very rubbish, the edge of the Microsoft's last Straw, he will certainly operate very well.

But if you want to take up less memory, take up less hard disk space, install a fixed old version, this is a better choice.

----------


## Schmidt

> Is there a necessity that the end-user systems (where my application is installed) also should have "evergreen WebView-runtime" installed in them (if not already installed)?


Yes, of course - but on each of the target-systems, this "base-runtime-installation" will only have to be done once
(as the "evergreen" suggests, this chromium-runtime will from this point on, be updated by the system).

As for detection, whether a given target-system already contains this runtime,
you can simply check the output of the GetMostRecentInstallPath-method: 
strInstallPath = WV.GetMostRecentInstallPath 

If it gives back an empty string, then you need to inform the user, 
to download the little 1.7MB base-installer from the MS-webpage via this (apparently constant) Link -
(as already given in the Opener-Posting of this thread):
https://go.microsoft.com/fwlink/p/?LinkId=2124703

If you ask your user beforehand like this:


```
  If Len(WV.GetMostRecentInstallPath) = 0 Then 'Edge-Chromium-Webview is missing on this system
     If MsgBox("The needed MS-WebView2-runtime is missing," & vbLf & "Do you want to download the installer now?", vbYesNo) = vbYes Then
        New_c.FSO.ShellExecute "https://go.microsoft.com/fwlink/p/?LinkId=2124703"
     End If
  End If
```

The little 1.7MB MS-Executable from that download above, will then determine which system the User actually runs (Win7, Win8, Win10) - 
and then download and install the larger (about 50MB-80MB) and properly matching evergreen-runtime which will work best on the given system.

HTH

Olaf

----------


## Schmidt

> But if you want to take up less memory, take up less hard disk space, install a fixed old version, this is a better choice.


Please stop giving misleading advice here in this thread.

Everything you've posted so far here (including your posts #72, #73, #74, #75) - 
contains only your usual nonsensical garbage.

Olaf

----------


## xiaoyao

Because at first I didn't know if. Net directly supported the standard version of the edge.
Just like ie, I thought the system came with WebBrowser controls.
After the win10, win11, the system recommended by default to install the edge browser software, using the Google kernel, if you can bring webview2 control is convenient, otherwise you need to install 500MB runtime.

I just like automatic installation and deployment.The original detection of whether the edge runtime is installed, it takes more than 10 seconds, so later found a way to find the registry.
I spent more than a day on it. I just hope others can avoid detours.
Then I stumbled on the silent installation method.

----------


## xiaoyao

Thank you for your contribution to the highly encapsulated Google kernel.
I just spent more than an hour reading everyone's replies.Many people do not know the problem they solved, but did not leave detailed code.
Is there a way to open the privacy page?
For example, create two webview objects in a form.
But the cookie between them is quarantine each other, is there such a setting?
If you create objects in multiple threads and use multiple webview controls in the same window, can you improve the running speed?

IE WebBrowser may run in the STA mode. If you create it in multi-thread, the webpage will not show, even if the creation is successful, the running speed is also very slow, and it is actually a message queue processing, eventually is running in the same thread. in.

----------


## xiaoyao

> Hi Olaf,
> 
> Is there a way to implement late-binding for WebView2? This is to handle a scenario where user has not yet installed pre-requisites (WebView2 Runtime and RC6).


After my test. The new computer is not installed with WebView Runtime, nor will it be wrong. This is a creating an object, I will be snatched 10 seconds, then the prompt fails. In this case, the automatic download of the runtime installer will be successfully created after the installation is complete.

There is also a problem, rc6.dll. Are there any plans to launch a 64-bit version?
In this way, VBA, 64-bit office, VB. Net and other IDE or development tools can also use it.
Twinbasic, and many other IDE alternatives to VB6 are under development, many of which can generate 64-bit exeThe biggest disadvantage of Microsoft's VB6 is that it does not support 64-bit, but VBA has a 64-bit version

Are there any plans to develop a simple webdriver like interface?
It just uses HTTP or websocket to control a properly installed Google Chrome or Edge browser.

You do not need to install a development version of edge or a webview runtime.

Almost eighty or ninety percent of computers have Google Chrome installed.
There is an open source project based on the COM interface of Google webview driver. But it hasn't been updated for many years.

A good technician can compile it to 64 bits.And add some of the latest version of the function, because there are some functions have been wrong or outdated.

----------


## xiaoyao

vb6 webdriver,support vba,call edge chrome,
msedgedriver.exe


Without systematic teaching materials, many people will only use simple open web pages.

I've tested this before, getting all the tabs, switching between any of them, and it's very time consuming to debug.

So if you can have a master sub-installed easier to use, many people will not need to learn to use.

JS, database, network programming, interface beautification, Google browser control, these areas have great market potential in the future.

https://blog.csdn.net/qq_24499417/ar...ails/105602339

https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

----------


## xiaoyao

Microsoft WIN11 preinstalled messaging APP teams 2.0 experience: Built on Edge Webview 2 2021-08-18

Just saw the news, the future win11 comes with a webview2 runtime.
There is no need to download and install it manually in the future, so it is much more convenient.

If we study webdriver more thoroughly, what browser is automatically detected on the client? Automatically download the driver, automatically open the web page and automatically fill in the form.

Applications such as Microsoft Office have begun to deploy WebView2 Runtime in their applications. WebView 2 Runtime has been installed on more than 200 million Windows devices.

----------


## saturnian

Hello Olaf
Is it possible to add the management of the new DownloadStarting event of webview2 in RC6 ?.
This would allow to change the default download directory.

Thanks a lot

François

Here is the link to Microsoft Documentation of this new event
WebView2 Win32 C++ ICoreWebView2_4 | Microsoft Docs

----------


## softv

> Have just finished a Binding to the new WebView2-BrowserControl (based on Edge-Chromium).
> ... .. .
> ... .. .
> The new BaseDll-package of the RC6 now includes the official WebView2Loader.dll (version 1.0.674),
> which the cWebView2-class then works against.
> ... .. .
> ... .. .
> You should now be able to test this new Edge-Browser-Binding (even on Win7-OSes) via this little VB6-Demo:
> ... .. .
> ...



Dear Olaf,

First thing first. *Thanks a TONNN*, as ever. It was great seeing your demo in action! Wow!

Actually, fortunate that I stumbled on this forum page (when I was really desperate to find a demo on how to use WebView2 in your RC6). How I wish all these demos of yours (or) links to these kinds of forum pages were in your vbRichClient.com website in one page! Anyway, I fully understand your lack of time. 

Well, you have asked us to let you know if something is not working. I am just giving hereunder what happened when I ran the demo:

1. For the following procedures, VB6 reported "Compile error: Procedure declaration does not match description of event or procedure having the same name"


```
Private Sub WV_AcceleratorKeyPressed(ByVal KeyState As eWebView2AccKeyState, ByVal IsExtendedKey As Long, ByVal WasKeyDown As Long, ByVal IsKeyReleased As Long, ByVal IsMenuKeyDown As Long, ByVal RepeatCount As Long, ByVal ScanCode As Long, IsHandled As Long)  
  Debug.Print "WV_AcceleratorKeyPressed"
End Sub
```



```
Private Sub WV_NavigationCompleted(ByVal IsSuccess As Long, ByVal WebErrorStatus As Long)
  Debug.Print "WV_NavigationCompleted"
End Sub
```

2. Instead of immediately researching on what the abovementioned error could be due to, I just commented out both the above procedures and ran the demo. And, there it was! Your demo in super action! *Thanks, Olaf!* People like you give lots of joy to persons like me!

Well, why did the compile error pop up for the abovementioned two procedures? Have they to be redeclared with different number/types of parameters? If so, kindly let me know how. In case the Compile error was due to some other reason, then *kindly educate me* on the same too.

Kind Regards.

----------


## jpbro

> Well, why did the compile error pop up for the abovementioned two procedures? Have they to be redeclared with different number/types of parameters? If so, kindly let me know how. In case the Compile error was due to some other reason, then *kindly educate me* on the same too.


See https://www.vbforums.com/showthread....=1#post5530453. Short-answer RC6 is still in a development phase and the method signatures are not yet finalized.

----------


## softv

> ... .. .
> As for detection, whether a given target-system already contains this runtime, ... .. .
> ... .. .
> If you ask your user beforehand like this:
> 
> 
> ```
>   If Len(WV.GetMostRecentInstallPath) = 0 Then 'Edge-Chromium-Webview is missing on this system
>      If MsgBox("The needed MS-WebView2-runtime is missing," & vbLf & "Do you want to download the installer now?", vbYesNo) = vbYes Then
> ...


Thanks a LOT, Olaf! I was thinking of doing the detection myself via a tiny function but then I also thought some function must be already existing. And, there it is! Thanks. 

Kind regards.

----------


## softv

Thanks jpbro. Both the procedures work now!

Kind regards.

----------


## saturnian

Hello,

Using RC6 cWebView2 with the latest Evergreen version of Webview2, on some sites (especially Google sites: Google News, Google Play Store ...) the DocumentURL and DocumentTitle properties remain an empty string once the page is completely displayed.
This does not happen with old fixed versions of webview2 !
Have you encountered this problem?
Is this a Microsoft regression or an RC6-Webview interface problem or Google sites issues ?
Best regards

Note: I am using RC6 6.0.9 on Windows 10

----------


## Schmidt

> Hello,
> 
> Using RC6 cWebView2 with the latest Evergreen version of Webview2, on some sites (especially Google sites: Google News, Google Play Store ...) the DocumentURL and DocumentTitle properties remain an empty string once the page is completely displayed.
> This does not happen with old fixed versions of webview2 !
> Have you encountered this problem?
> Is this a Microsoft regression or an RC6-Webview interface problem or Google sites issues ?


I was able to reproduce that, and the reason is, that Google since a few weeks apparently insists (on some of their Sites) on "higher security" for the eval-function (when called from "self-assigned scripts" - which I use so far, to resolve window-Properties via jsProp Get/Let - as e.g. jsProp("document.title").

Came up with a workaround for the Eval-Function (which formerly worked behind WV.jsProp Get/Let) -
 and it will be present in the next Release 6.0.10... (want to wait until SQLite 3.37 gets released at december 1'th)

Olaf

----------


## saturnian

> I was able to reproduce that, and the reason is, that Google since a few weeks apparently insists (on some of their Sites) on "higher security" for the eval-function (when called from "self-assigned scripts" - which I use so far, to resolve window-Properties via jsProp Get/Let - as e.g. jsProp("document.title").
> 
> Came up with a workaround for the Eval-Function (which formerly worked behind WV.jsProp Get/Let) -
>  and it will be present in the next Release 6.0.10... (want to wait until SQLite 3.37 gets released at december 1'th)
> 
> Olaf


thank you for these details, Olaf
I will wait for RC6 version 6.0.10.
Thank you again for this fantastic work !

François

----------


## I. Capri

// Deutsch
Sehr geehrter Herr Schmidt,

ich hätte gern gewusst, ob Sie das webResourceRequested-Event in RC6.DLL zur Verfügung stellen können, sowie wie Sie ans ICoreWebView2-Interface dran kommen können.

Vielen Dank im Voraus für Ihre Rückmeldung!

Mit freundlichen Grüßen
Igli Kapri

// Englisch
Dear Mr. Schmidt,

I would like to know whether You can provide the webResourceRequested-Event in RC6.DLL as well as how You find the ICoreWebView2 interface in .NET.

Thank you very much in advance for Your response!

Kind regards,
Igli Kapri

----------


## workmail

vb6+cwebview2 is good thing

but did somebody know why could not upload file in vb6 cwebview2 edge browser?

some web could, but most important web could not use web file upload system. What a pity.

----------


## talatoncu

How can I click a button on the page?

I have tried

         WV.jsRun ("document.getElementById('btnSubmit').click")

But nothing happened

----------


## WZabel

In WebViewInit
 'we can predefine our own set of js-functions, before any document gets loaded
WV.AddScriptToExecuteOnDocumentCreated "function ElementClick(myElement){ window.document.getElementById(myElement).click(); }"

'after document load we can use
WV.jsRun "ElementClick", "btnSubmit"

----------


## Schmidt

> WV.jsRun ("document.getElementById('btnSubmit').click")


jsRun is thought for function-calls, which allow you to pass parameters as normal VB-Vars.

For such longer "multi-dotted-expressions" (with "inner, literal-arguments"), you are better advised to use:
WV.ExecuteScript "document.getElementById('btnSubmit').click()" 

Please note the trailing parentheses behind the last methodname "click".

Olaf

----------


## talatoncu

> jsRun is thought for function-calls, which allow you to pass parameters as normal VB-Vars.
> 
> For such longer "multi-dotted-expressions" (with "inner, literal-arguments"), you are better advised to use:
> WV.ExecuteScript "document.getElementById('btnSubmit').click()" 
> 
> Please note the trailing parentheses behind the last methodname "click".
> 
> Olaf


Perfect!

Thank you very much Sir!

You saved my life with this implementation and your immediate answer.

----------


## EasyOneX

Hi. 

Unfortunately, due to the security feature of the Edge Browser, I cannot access local files, e.g. something like this: file: /// C: /Pictures/loading.gif

Error message in the console: Not allowed to load local resource

How can I change the security settings to allow local resources?

thx Andreas

----------


## Schmidt

> Unfortunately, due to the security feature of the Edge Browser, I cannot access local files, e.g. something like this: file: /// C: /Pictures/loading.gif
> 
> Error message in the console: Not allowed to load local resource
> 
> How can I change the security settings to allow local resources?


There's a huge deal of influence possible, via the CommandLine-Parameter of the intial Binding-Call...

I've posted a Link to it already in an earlier posting here in this thread,
but here is it again (already jumping to a setting which might work for you):
https://peter.sh/experiments/chromiu...ess-from-files

If this specific one doesn't, other flags might do the job (perhaps google a bit about it,
using the term CEF in your searches).

Olaf

----------


## EasyOneX

> There's a huge deal of influence possible, via the CommandLine-Parameter of the intial Binding-Call...
> 
> I've posted a Link to it already in an earlier posting here in this thread,
> but here is it again (already jumping to a setting which might work for you):
> https://peter.sh/experiments/chromiu...ess-from-files
> 
> If this specific one doesn't, other flags might do the job (perhaps google a bit about it,
> using the term CEF in your searches).
> 
> Olaf


Perfect. I hadn't seen the page with the commandlines yet. That's great. Thank you very much and happy holidays I wish you...

Thx Andras

----------


## EasyOneX

Thanks for the link. I hadn't seen the website yet. I wish many dear and happy holidays...

----------


## xxdoc123

I know that using chromedirver. can intercept the image of the specified element
  By the following command
/session/" & m_StrSessionId & "/element/" & m_StrElementId & "/screenshot.




> Private Sub cmdCaptureWV_Click()
>     Dim Srf As cCairoSurface
>     Set Srf = WV.CapturePreview(CaptureAs_PNG)   'capture the current WV-Window as a Cairo-Image-Surface
>     Srf.WriteContentToPngFile App.Path & "\WV_Capture.png" 'which we can now visualize, or just write out as a PNG-file
> End Sub


Do you support this function?

----------


## Schmidt

> I know that using chromedirver. can intercept the image of the specified element
>   By the following command
> /session/" & m_StrSessionId & "/element/" & m_StrElementId & "/screenshot.
> 
> Do you support this function?


No, there's no Element-based ScreenShot-feature (what's built-in, is working Window-based).
One could get around making that "bigger ScreenShot" - 
then getting the surrounding rect of the Element via javascript -
followed by cutting out the Sub-Bitmap using these coords...

But if this is for Unit-Testing... that's what chromedriver is made for and specialized in
 (not only with regards to the ScreenShot-feature) ... so, why not use it furhter?

Olaf

----------


## xxdoc123

We know that Google Chrome can set the capabilities parameter to customize the functions of the browser through chromdirver. I dont know if you have this setting.For example: disable camera ...


I want to replace the js function loaded in the original webpage.how can i do
Originalfunnctio is checkCamera

WV.ExecuteScript "checkCamera= function myfunction(){}" ?

----------


## xxdoc123

We know that Edge-Chromium can set the capabilities parameter to customize the functions of the browser through Edgedirver. I dont know if you have this setting.For example: disable camera ...


I want to replace the js function loaded in the original webpage.how can i do
Originalfunnctio is checkCamera

WV.ExecuteScript "checkCamera= function myfunction(){}" ?

----------


## Schmidt

> I dont know if you have this setting.For example: disable camera ...


As already said a few posting further above - there is a ton of startup-settings,
you can set and combine via the commandline-parameter of the initial Bind-Call.

Here is the link again: https://peter.sh/experiments/chromiu...line-switches/
(if you search via <Ctrl><F>, you will find a lot things to influence "media" or "capture"-behaviour.)

Olaf

----------


## xxdoc123

thanks. 

I am not very proficient in JS.I have to try to use Js.

----------


## meco_r

Hi Olaf and  thanks for your great work!
I have a "stupid issue" to report regarding UserContextMenu event: the ScreenY argument declaration is spelled wrong: "SreenY"  :Smilie:  
Someting more serious: are you planning to map the NavigationStarting Event in the vb6 wrapper so that is possible to detect the destination url before the navigation effectively occurs?

Ciao,
DR

----------


## Resurrected

Hi Olaf

I have a question regarding RC6.WebView2.

Is there a way to download an image resource instead of opening it in WebView2? By using Navigate, the image is opened in WebView2 instead of invoking the download operation. I'd like that image to be downloaded the way I navigate to a zip file.

Well, I know I could get the image url and use a separate httpclient to download the file. But anyway to use the WebView2?

Plus it doesn't seem the RC6.WebView2 provide anything related to downloading.

Thanks in advance.

----------


## C--E

Hello,

I downladed RC6 a few days ago from vbRichClient.com and I registered RC6.dll with the aid of RegisterRC6inPlace.vbs.
Then I installed the "evergreen-WebView2-runtime" via the MS-download-link.

I tried to run WebView2Demo.vbp, got the error "Procedure declaration does not match description ..." and corrected the code as explained in post #60.

Now I expected the demo to run, but it always stops in the following line:


```
If WV.BindTo(picWV.hWnd) = 0 Then MsgBox "couldn't initialize WebView-Binding": Exit Sub
```

with the following error message:
*"Runtime Error 53:
Error in FindFirstFile: ErrNum: 3, The system cannot find the path specified."*

(I'm using VB6 Version 8176 under Win10Pro).

Any ideas what is wrong or what I did wrong?

----------


## Schmidt

> Hello,
> 
> I downladed RC6 a few days ago from vbRichClient.com and I registered RC6.dll with the aid of RegisterRC6inPlace.vbs.
> Then I installed the "evergreen-WebView2-runtime" via the MS-download-link.
> 
> I tried to run WebView2Demo.vbp, got the error "Procedure declaration does not match description ..." and corrected the code as explained in post #60.
> 
> Now I expected the demo to run, but it always stops in the following line:
> 
> ...


There seems to be a problem with the installation of the WebView-Runtime...

The BindTo-call is looking for the WebView-Runtime-BaseFolder via the following Path-Expression:
(for your Immediate-Window):
?New_c.FSO.GetSpecialFolder(CSIDL_PROGRAM_FILESX86) & "\Microsoft\EdgeWebView\Application"

When I paste the above into my immediate-window (followed by pressing <Return>),
then it prints out:
C:\Program Files (x86)\Microsoft\EdgeWebView\Application

This path exists on my machine (when I paste it into Explorer.exe, it shows the content)...

Under this path, the BindTo-call then continues, to list determine the Folder with the highest Version-Number...

So, could you check what your immediate-window says, the Base-InstallPath of the WebView-runtime is - 
and whether it exists on your machine?

HTH

Olaf

----------


## C--E

The output of the Immediate Window is: C:\Program Files (x86)\Microsoft\EdgeWebView\Application
This path does not exist on my machine!

Some minutes ago I re-installed "evergreen-WebView2-runtime" via the MS-DownloadLink, which took place without problems (which was also the case during the first installation), and now the path \EdgeWebView\Application exists and the demo program is running!

Thank you very much for your quick help!

----------


## xxdoc123

Save As is not available in web pages

----------


## Schmidt

> Save As is not available in web pages


"Save As..." is available in the Default-Context-menu...
and it will work, when you do not run elevated as an Administrator (as is the case e.g. in the IDE)...

When you run a compiled version, it should pop-up the FileDialog (for you to choose a Save-target).

(MS knows about the problem in Admin-Mode, there is a ticket for it: https://github.com/MicrosoftEdge/Web...ack/issues/802)

HTH

Olaf

----------


## xxdoc123

thanks

----------


## C--E

Once again thanks to Olaf for his help and generally for his great work!

Now I'm succesful with the WebView2Demo.vbp, added a second picturebox named "Pchart" and wanted to copy the let's say "browsing result", i.e. the image in picWV, into this second picturebox. I tried:
_PChart.Picture = picWV.Image_
but obviously that doesn't work.
Any ideas on how to get this done?

----------


## Schmidt

> _PChart.Picture = picWV.Image_
> but obviously that doesn't work.


The PictureBox picWV which is used in the Demo, is only providing "a Container-hWnd" for the Browser-instance,
(which places its own Browser-hWnd as a Child inside the picWV.hWnd).

But there is a builtin Method, which captures the current Browser-Content as a Pixel-Graphic
(returning a cCairoSurface-Object, which you can use for all kind of purposes, e.g. writing to a PNG-ByteArray or -File for example)

Long story short - please try: 
Set PChart.Picture = WV.CapturePreview(CaptureAs_PNG).Picture

Olaf

----------


## C--E

I saw the following part in the demo:
_  Dim Srf As cCairoSurface
  Set Srf = WV.CapturePreview(CaptureAs_PNG) 'capture the current WV-Window as a Cairo-Image-Surface
  Srf.WriteContentToPngFile App.Path & "\WV_Capture.png" 'which we can now visualize, or just write out as a PNG-file
_but was not able to transform this into the syntax:
_Set PChart.Picture = WV.CapturePreview(CaptureAs_PNG).Picture_

Long story short: You code works like a charm - thank you very much!!!

Best Regards
C-E

----------


## Schmidt

> I saw the following part in the demo:_
> ..._was not able to transform this into the syntax:
> _Set PChart.Picture = WV.CapturePreview(CaptureAs_PNG).Picture_


The above "one-liner" is just making use of a compiler-feature,
which creates a (hidden) temporary cCairoSurface-instance under the covers,
(from the return-value of the CapturePreview-method) before accessing its Picture-Property...

The PNG-output code could have been written in one line as well - 
I just wanted to make it more obvious, what CapturePreview returns.

A cCairoSurface is just a wrapper-class around a "32Bit-Per-Pixel DIB-allocation" in system- (not GPU-) memory -
but also the entry-point into powerful cairo-based (Vector-)Drawing-Commands, which are just "one context-call" away.

E.g. you could easily draw "additional stuff on it" (before placing such a Surface on a PictureBox),
for example - if you want to "frame" the Browser-ScreenShot, you could do it this way:


```
  Dim Srf As cCairoSurface 'make the returned Surface explicit
  Set Srf = WV.CapturePreview(CaptureAs_PNG)
  With Srf.CreateContext 'enter Drawing-Mode
    .SetLineWdth 2
    .Rectangle 0, 0, Srf.Width, Srf.Height, True 'define a Rectangle-Path
    .SetSourceColor vbRed, 0.5 'define the Border-Color with 50% Alpha
    .Stroke 'strokes only the Outline of the Path (not the interiour of the Rect)
  End With
  Set PChart.Picture = Srf.Picture 'now assign the combined result to the PicBox
```

HTH

Olaf

----------


## EasyOneX

Hi, everyone.

Also, is it possible to auto-fit a text box to the available width and height so that when the shape is resized, the text box will also resize proportionally to the available area?

From this :


```
<textarea id=txt1 cols=50 rows=4></textarea>
```

to this:


```
<textarea id=txt1 height:auto width:auto></textarea>
```

Kind regards

Andrew

----------


## Bearfot

@Olaf First of all fantastic work!! One question:
Would it be possible to extend cWebView2 with a callback when basic authentication is requested from a site so I can provide with user name and password and thereby prevent the Sign in prompt? I.e. my hybrid app first requires a login by the user, and when navigating to my site an additional "Sign in" is currently now needed. Earlier when using the embedded IE control this was automatically handled by WinInet.

Thanks in advance

----------


## Bearfot

Hi again,
what is the difference between providing arguments in the New_c.WebView2(...) compared to BindTo(...)? 
I.e. adding userDataFolder and additionalBrowserArguments seems only have to affect in BindTo(), and also it seems that even the arguments are optional I can't just provide the additionalBrowserArguments without also specifying a userDataFolder. If userDataFolder is left empty or as an empty string, BindTo will fail.

regs
Stefan

----------


## Schmidt

> what is the difference between providing arguments in the New_c.WebView2(...) compared to BindTo(...)?


None ... 
The only difference is, that the optional timeout-param is a bit shorter (5sec) behind New_c, than in BindTo (8sec) -
though this might exactly be the difference on some older (slower) machines between the two calls.
I have corrected that timeout-difference in the cConstructor-call to 8sec now (to match with BindTo).




> I.e. adding userDataFolder and additionalBrowserArguments seems only have to affect in BindTo(),


All the Params are just "routed through" to BindTo, as they come in via New_c.WebView2 -
 (the only exception - as said - being a different timeout, when you leave this param-slot free).




> and also it seems ...
> I can't just provide the additionalBrowserArguments without also specifying a userDataFolder.
>  If userDataFolder is left empty or as an empty string, BindTo will fail.


If userData is left empty, the BindTo-call will internally not "leave it that way", but initialize it to:
If Len(userDataFolder) = 0 Then userDataFolder = New_c.FSO.GetLocalAppDataPath
(which resolves e.g. on my Win10 to: C:\Users\Olaf\AppData\Local)

Perhaps certain commandline-arguments only work with certain UserDataFolder-Paths 
(which might also depend on the OS-version you are using - I've heard of Users who have had problems on Win7)...

As for your earlier question... I think "finding the right HTML5" (and Css- or style-attributes) 
is in the responsibility of the Users of this control-binding (to not blow this thread here "out of proportion") -
and would suggest to post your HTML-questions in a better matching Forum (or SubForum on this site).

HTH

Olaf

----------


## Bearfot

@Olaf, thanks for reply!




> As for your earlier question... I think "finding the right HTML5" (and Css- or style-attributes) 
> is in the responsibility of the Users of this control-binding (to not blow this thread here "out of proportion") -
> and would suggest to post your HTML-questions in a better matching Forum (or SubForum on this site).


My earlier question was regarding basic authentication. If it was possible to get a callback from cWebView2 and provide user name and password in order to prevent the Sign in prompt (if a site uses basic authentication). E.g. something like GetCredentials(ByVal Url As String, UserName As String, Password As String, Cancel As Boolean).

regs
Stefan

----------


## Schmidt

> My earlier question was regarding basic authentication.


Oops, my bad (interchanged your post with that from Andrew/EasyOneX)...




> If it was possible to get a callback from cWebView2 and provide user name and password in order to prevent the Sign in prompt (if a site uses basic authentication). E.g. something like GetCredentials(ByVal Url As String, UserName As String, Password As String, Cancel As Boolean).


I don't know what exact behaviour you relate to, when you talk about "WinInet-usage" in conjunction with the old IE-Control.

If you "already know" the user-credentials from an earlier "logon-attempt"...
then the basic-auth credentials can be passed directly in the URL, as e.g.:


```
"http://username:password@example.com/"
```

There's also a lot of different "auth"-related params for the commandline... you might want to experiment with.

And finally, there's (since 6.0.9) a new method:
- NavigateWithWebResourceRequest (which has an optional param: Headers_CrLfSeparated As String)
which will allow you to specify headers like e.g.: "Authorization: Basic <your base64-encoded credentials>"

HTH

Olaf

----------


## Bearfot

Yes, passing username :Stick Out Tongue: assword in the url is how I now currently solved it, but that is not a preferable solution from a security perspective. 
Instead username/password should not be provided unless the site requests for it, and with a callback I can check if I have the proper credentials for the url, and in that case provide them or otherwise set cancel = true which will bring up the default Sign in prompt. Just a proposal for a nice feature for the future :-)

Thanks again
Stefan

----------


## xxdoc123

When I execute the js command,
WV.AddScriptToExecuteOnDocumentCreated jscode
WV.jsRunAsync "GetLinks", "div.picList > ul > li>a" '. error Unable to read   in WV_JSAsyncResult. .

if changed to

WV.AddScriptToExecuteOnDocumentCreated jscode
sleep 1000
WV.jsRunAsync "GetLinks", "div.picList > ul > li>a" '.
execution succeed. Is there a better way without sleep?

Also execute WV.ExecuteScript "document.querySelector('#app > div > section > aside > span').click();" sometimes the webpage is not executed successfully. So I will modify it to
WV.ExecuteScript "document.querySelector('#app > div > section > aside > span').click();"
sleep 1000
WV.ExecuteScript "document.querySelector('#app > div > section > aside > span').click();"
sleep 1000
WV.ExecuteScript "document.querySelector('#app > div > section > aside > span').click();"

Is there any good way to wait for js to finish executing synchronously?


How is the jsCallTimeOutSeconds function used?

----------


## avinash7

Hi Olaf, 

Thank you for such a great contribution. I was able to achieve most of the task that I need to.

However, I am unable to handle below scenarios:

1. Handle multiple downloads: I want to enable this by default to allow multiple file download (disable multiple file download confirmation). This is because I perform very lengthy process which ends with downloading multiple files which is currently blocked after downloading first file.

2. Default file download location: How to specify default file download location?

I tried to play with %appdata%\EBWebView\Default\Preference file that stores this settings. However, this file is overwritten automatically by some process every few seconds which causes reversal of my changes.

Also, I see that WebView2 has *DownloadStarting* event that allows to achieve some part of above, but I do not see that available in cWebView2.

----------


## Bearfot

Hi Olaf,
if you have any plans of extending the cWebView2 events (e.g. DownloadStarting) then also the *DocumentTitleChange* is of interest. I have solved it now by adding the following code in the DocumentComplete event:
    m_webView.ExecuteScript "document.addEventListener('DOMSubtreeModified', function(e){if(e.target.nodeName === 'TITLE') vbH().RaiseMessageEvent('OnTitleChange',e.target.text)})"
This is maybe not the most efficient solution, but at least it works.

In addition I'm also very interested in getting access to "CoreWebView2EnvironmentOptions". Its property "AdditionalBrowserArguments" can be applied in the constructor and BindTo method, but is is possible to access the "Language" and "AllowSingleSignOnUsingOSPrimaryAccount" properties?

Finally in order to solve my earlier WinInet issues there seems to be a solution by copying cookies from WinInet to WebView2, but it would the require access to the "CoreWebView2CookieManager" object. Any plans to make such extensions of the cWebView?

regs
Stefan

----------


## Bearfot

Hi again Olaf,
one more question. I found a bug when adding an object using the AddObject() method which I guess internally calls the "AddHostObjectToScript". It seems that you can't access an attribute named "length" of such object. The solution I found was to add the following line for the created javascript proxy object:
var myobject = window.chrome.webview.hostObjects.sync.myobject; // myobject with a "length" attribute added with cWebView2.AddObject()
alert(myobject.length); // will always display 0
// adding the following solves the issue
myobject._forceRemoteProperties.add("length"); // myobject is actually a proxy object in javascript
alert(myobject.length); // now shows the correct value of myobject.length

As I don not know the implementation details, is this a bug in cWebView2.AddObject() or something I should report in github for CoreWebView2.AddHostObjectToScript()?

regs
Stefan

----------


## saturnian

Hello avinash7 and Bearfot


Olaf seems to rarely respond to requests to add functionality to RC6. It's probably to avoid putting pressure on himself. The task he has set himself is indeed  hudge.
In a recent conversation, he told me he hoped to integrate Webview2 download management in version 6.0.10 of RC6. I look forward to this version to continue my developments. I even check every day if the new version is posted on his site!
We'll have to be patient  :Smilie: 
Thanks again to Olaf for his fantastic work !

----------


## Bearfot

The AddHostObjectToScript issue is confirmed bug in webview2 (issue #2185) so this can be ignored. 
Access of the cookie manager can also be skipped as this seems not solve my issue. 
Other things just nice to have, so no remaining issues from me.

----------


## avinash7

> It's probably to avoid putting pressure on himself


Sorry Olaf and saturnian if it looked like creating pressure. I posted here to see if there is anything already available and can be leveraged to achieve what I wanted to do. This is because I see that Olaf has surfed breadth and depth of this area!

----------


## BhargaviU

> Have just finished a Binding to the new WebView2-BrowserControl (based on Edge-Chromium).
> 
> I've included this Binding (all in a single Class, named cWebView2) in the new RC6-version of the RichClient-lib
> (please download this new version 6 from its usual place, at vbRichClient.com first).
> 
> The new BaseDll-package of the RC6 now includes the official WebView2Loader.dll (version 1.0.674),
> which the cWebView2-class then works against.
> 
> Please note, that the above Binding will currently require, that you install the larger:
> ...


Hi Schmidt, 
I tired WebView2Demo it is really great. I wanted to know if we can integrate events of webbrowser1 with its replacements in WebView2.
For Example :
1.StatusTextChange
2.BeforeNavigate2
3.WindowClosing

I tried few events but was unable to recreate the events I mentioned before.
Could you please guide me for the same.

----------


## LeandroA

Hi is it possible to get an object with jsProp, getElementsByClassName doesn't work for me either.



```
Dim Elements As Object
Set Elements = Document.GetElementsbyClassName("FTBzM")
```

with IE this worked, should I think about it differently?

----------


## BooksRUs

I'm new to all this, so take it easy on me, please  :Smilie: 

I have successfully used the WebView2 in the VB6 IDE without issues... BUT, when I go to MAKE my project, it fails to compile with the following error:

*Unexpected error occurred in code generator or linker. --View error messages?*

I click on Yes and get a text tmp file that contains this error:

C:\<MYFOLDER>\<MYFORM>.frm(6624) : *fatal error C1001: INTERNAL COMPILER ERROR*
*		(compiler file 'e:\work\utc2\src\P2\main.c', line 495)*
*    Please choose the Technical Support command on the Visual C++*
*    Help menu, or open the Technical Support help file for more information*

If I comment out any lines where I'm doing this:

*Set wv5 = New_c.WebView2* 

or this:

*If wv5.BindTo(... blah, blah... ) then*

Then the program compiles fine.  Obviously, it doesn't *work* correctly because these lines are commented out.

Again, if I just Run the program in the VB6 IDE, then it works great.

Please help.

----------


## SearchingDataOnly

> I'm new to all this, so take it easy on me, please 
> 
> I have successfully used the WebView2 in the VB6 IDE without issues... BUT, when I go to MAKE my project, it fails to compile with the following error:
> 
> *Unexpected error occurred in code generator or linker. --View error messages?*
> 
> I click on Yes and get a text tmp file that contains this error:
> 
> C:\<MYFOLDER>\<MYFORM>.frm(6624) : *fatal error C1001: INTERNAL COMPILER ERROR*
> ...


Maybe it's a question about the RC6 path.
https://www.vbforums.com/showthread....=1#post5443031

----------


## BooksRUs

> Maybe it's a question about the RC6 path.
> https://www.vbforums.com/showthread....=1#post5443031



I used the included RegisterRC6inPlace.vbs to register RC6 on my dev PC, directly inside my App folder, in hopes that nothing would be confused as to where anything was.

I did extract all the DLL files into this same folder.  Does any of the other DLLs need to be registered just so the VB6 can compile an EXE that uses RC6?

Thanks!

----------


## Schmidt

> I used the included RegisterRC6inPlace.vbs to register RC6 on my dev PC, directly inside my App folder, in hopes that nothing would be confused as to where anything was.
> 
> I did extract all the DLL files into this same folder.  Does any of the other DLLs need to be registered just so the VB6 can compile an EXE that uses RC6?
> 
> Thanks!


If it runs in the IDE, then there is nothing wrong with the registration of RC6 -
so the compiler-error you see has to have other reasons - like e.g.:
- you're not running the IDE "as Admin" (when compiling)
- you're not using the most recent ServicePack for the VB6-IDE
- you've registered the RC6 on a Network-Path, or a "mapped Network-Drive"
- you've opened your VB-Project from a Network-Path or a "mapped Network-Drive"
- you're trying to compile the Binary "into a Network-Path or a mapped Network-Drive"

I'd start trying to fix this, by ensuring Admin-Mode for the IDE -
and try to "open, and compile to" from/to local Folders on local Disks...
(also making sure, that "compiling Debug-info into your Executable" is deactivated in the IDEs compiler-settings)

HTH

Olaf

----------


## BooksRUs

> If it runs in the IDE, then there is nothing wrong with the registration of RC6 -
> so the compiler-error you see has to have other reasons - like e.g.:
> - you're not running the IDE "as Admin" (when compiling)
> - you're not using the most recent ServicePack for the VB6-IDE
> - you've registered the RC6 on a Network-Path, or a "mapped Network-Drive"
> - you've opened your VB-Project from a Network-Path or a "mapped Network-Drive"
> - you're trying to compile the Binary "into a Network-Path or a mapped Network-Drive"
> 
> I'd start trying to fix this, by ensuring Admin-Mode for the IDE -
> ...



First, I want to say a big THANKS to Olaf, for all your hard work on all of these tools!  Also, for your time to jump in and try to help me out.  Right away, *none* of the suggestions you have apply, I double-checked them all.

The particular form I'm adding this to is the "main" form for a pretty large program that has been my project for the last 13 years.  It is on the edge of having more controls than VB6 allows, so I thought perhaps having to declare WV (with events) was pushing it over the limit.  I don't know if it's possible, but it would be wonderful if we could have an ARRAY of WV (with events).  I'm not sure if these declarations "count" towards the VB6 limits or not, but either way, this would allow an array of WV that match an array of PicBoxes that "host" the WVs that I want to use the in program (there are several).  This is exactly how I'm implementing this with the Webbrowser controls that I'm trying to replace.

Anyway, I went "back to basics" and tried to compile the sample program and it compiled right up without problems AND it actually works when Run, both in the IDE and the EXE.

So, I *moved* these statements:
   Set wv5 = New_c.WebView2
   If wv5.BindTo(FZwv(5).hwnd, , "C:\<myfolder>\EdgeWebView") = 0 Then

... to the Form_Load event (as in the Demo program) and the program now *does* Compile, but it does *not* work.  For some reason, in my program, it seems to want me to do the BindTo again in order to work correctly...

Perhaps, this is because the PicBox isn't really visible YET in the Form_Load event?  Does the PicBox actually *have* to be Visible in order for the BindTo to work correctly?  The main form isn't yet visible in the load event, it's busy loading...  AND the user has yet to actually do anything that will make the WV/PicBox visible in the program, as this is an option for the user to turn this on or off.

Again, Thanks for all your work on this and other tools over the years.

----------


## wwolf

> Perhaps, this is because the PicBox isn't really visible YET in the Form_Load event? Does the PicBox actually *have* to be Visible in order for the BindTo to work correctly? The main form isn't yet visible in the load event, it's busy loading... AND the user has yet to actually do anything that will make the WV/PicBox visible in the program, as this is an option for the user to turn this on or off.


That's right! The window to whose hwnd the WebView is bound must be visible. This can be quite tricky with modal windows. 

In my sample code, I do something like this: https://www.vbforums.com/showthread....mo-application

----------


## BooksRUs

> That's right! The window to whose hwnd the WebView is bound must be visible. This can be quite tricky with modal windows. 
> 
> In my sample code, I do something like this: https://www.vbforums.com/showthread....mo-application


It appears that the entire project is not based on normal VB6 forms.  Without a total rewrite, are there some snippets of code that I could possibly use to get passed the Visible requirement, or to trick it into working?

Thanks!

----------


## Schmidt

> Perhaps, this is because the PicBox isn't really visible YET in the Form_Load event?


Yes, the PicBox.hWnd (any hWnd) you bind to, 
has to be visible at the point you call WV.BindTo...

And any hWnd-based Child-Control will report False (regarding its visibility),
as long as its hosting TopLevel-Parent is still invisible (in your case, your Form).

Please take another look at the first line in my original Demo-Codes Form_Load (and the comments I made there).

Olaf

----------


## BooksRUs

> Yes, the PicBox.hWnd (any hWnd) you bind to, 
> has to be visible at the point you call WV.BindTo...
> 
> And any hWnd-based Child-Control will report False (regarding its visibility),
> as long as its hosting TopLevel-Parent is still invisible (in your case, your Form).
> 
> Please take another look at the first line in my original Demo-Codes Form_Load (and the comments I made there).
> 
> Olaf



Thanks again, Olaf.  I spent alot of time trying different things, but I feel like I'm spinning my wheels because I was getting away from the *real* problem.  I can live within the parameters of when to be Visible and when to SET & BINDTO, as the program is actually *working*.

The real problem is that the program won't *compile*.  So, I tried different settings on the VB6 compiler dialog -- it appears that the only way I can get it to compile is to change it to Compile to P-Code.  Any other setting I tried with a working program, would generate the compiler error in the original post.

Only time will tell if I'm able to keep these settings and distribute without causing other unknown issues, but I'm going to give it a try.

Thanks again for helping me out.  If there's anything else I can provide that might help solve the issue, just let me know.

 :Smilie:

----------


## BooksRUs

> WV.jsRun is thought for simple (for the most part, self-defined) functions...
> 
> For more complex "actions" like yours above, try it with:
> WV.ExecuteScript "document.getElementById('Somebutton').click()"
> instead.
> 
> HTH
> 
> Olaf



I'm trying to simply automatically login to a website.  I'm replacing a VB6 webbrowser control.  I have already analyzed the login page and I know the fields I want to fill in are "user_name" and "user_password".  The login button is on the first (0) form on the page.  So, I used to do this:

set w=webbrowser.Document
set f=w.forms.item(0)
set e=f.elements
e.Item("user_name").Value = <myuserid>
e.Item("user_password").Value = <mypassword>
f.submit


My question is, how do I do this with the new WebView since the DOM is not there, and the Submit button doesn't *have* a name?

Thanks!

----------


## Schmidt

> My question is, how do I do this with the new WebView since the DOM is not there...


The DOM is there, but you have to interact with it in js now... 
(cWebView2 is making this easy via AddScriptToExecuteOnDocumentCreated)



```
With New_c.StringBuilder

    .AddNL "function submitLoginForm(usr, pwd){"
    .AddNL "   var f = document.forms[0]"
    .AddNL "       f.elements['user_name'].value     = usr"
    .AddNL "       f.elements['user_password'].value = pwd"
    .AddNL "       f.submit()"
    .AddNL "}"

    wv.AddScriptToExecuteOnDocumentCreated .ToString
  End With
```

Such an "extension-function" can be added before you navigate to a certain page.

Only the usage of this function - e.g. via:
wv.jsRun "submitLoginForm", "myUsrID", "myPwd"

has to be done after the document was loaded (e.g. from within Navigation_Complete or Document_Complete)

Olaf

----------


## BooksRUs

> The DOM is there, but you have to interact with it in js now... 
> (cWebView2 is making this easy via AddScriptToExecuteOnDocumentCreated)
> 
> 
> 
> ```
> With New_c.StringBuilder
> 
>     .AddNL "function submitLoginForm(usr, pwd){"
> ...



Cool, thanks for the info.  A few questions:

1. Once I inject this function, is it "persistent" upon each subsequent Navigate event, or is it just good for *one* Navigate, then it goes away?

2. Is there a way to "peruse" the DOM with WV?  Sometimes I have to basically "dump" all of the forms and elements of a page in order to find/pick out the particular form, element or field that I need to match, fill in, check, or click.

3. How do I "click" a button that doesn't seem to have a name?

----------


## Schmidt

> 1. Once I inject this function, is it "persistent" upon each subsequent Navigate event, or is it just good for *one* Navigate, then it goes away?


It is persistent (on that bound wv-instance) for all subsequent navigations - 
basically ensuring "your own set of global js-helper-functions"... -
(which BTW could also be aggregated in a normal "myGlobalHelpers.js" File for better editability,
and then added in one go like this: 
wv.AddScriptToExecuteOnDocumentCreated New_c.FSO.ReadTextContent(App.Path & "\myGlobaHelpers.js")




> 2. Is there a way to "peruse" the DOM with WV?


Sure, you can even get "visual assistance" on a loaded DOM, by opening the "Chrome-Inspector" via:
wv.OpenDevToolsWindow




> 3. How do I "click" a button that doesn't seem to have a name?


You could learn to use "selector-string-expressions" via e.g.:
- document.querySelector("<your selector string>")  https://developer.mozilla.org/en-US/.../querySelector
- SomeElement.querySelector("<your selector string>") https://developer.mozilla.org/de/doc.../querySelector

Selector-Strings are extremely powerful (they allow to search for any attribute, parent/child-relation and so on...)

At the end of the day, there's no way around doing all your "DOM-stuff" in javascript ...
but it has to be said, that this usually requires less lines of code, compared to VB6/IE-COMbased-DOM-parsing.

Olaf

----------


## wwolf

> 1. Once I inject this function, is it "persistent" upon each subsequent Navigate event, or is it just good for *one* Navigate, then it goes away?


Click on different links on the Google page and watch out for the alert window:



```
Option Explicit
Private WithEvents WV As cWebView2
Private Sub Form_Activate()
    If WV Is Nothing Then
        Set WV = New_c.WebView2(Me.hWnd)
        WV.AddScriptToExecuteOnDocumentCreated "function getSiteTitle(){alert (document.title)}"
        WV.Navigate "http://www.google.com"
    End If
End Sub
Private Sub Form_Resize()
    If WindowState <> vbMinimized Then
        If Not WV Is Nothing Then WV.SyncSizeToHostWindow
    End If
End Sub
Private Sub WV_DocumentComplete()
    WV.jsRun "getSiteTitle"
End Sub
```





> 2. Is there a way to "peruse" the DOM with WV?  Sometimes I have to basically "dump" all of the forms and elements of a page in order to find/pick out the particular form, element or field that I need to match, fill in, check, or click.




```
Option Explicit
Private WithEvents WV As cWebView2
Private Sub Form_Activate()
    If WV Is Nothing Then
        Set WV = New_c.WebView2(Me.hWnd)
        WV.Navigate "http://www.google.com"
    End If
End Sub
Private Sub Form_Resize()
    If WindowState <> vbMinimized Then
        If Not WV Is Nothing Then WV.SyncSizeToHostWindow
    End If
End Sub
Private Sub WV_DocumentComplete()
    Debug.Print "Source: " & WV.jsProp("Array.prototype.slice.call(document.getElementsByTagName('INPUT')).join(';')")
End Sub
```




> 3. How do I "click" a button that doesn't seem to have a name?


https://stackoverflow.com/questions/...706236#2706236

----------


## BooksRUs

> The particular form I'm adding this to is the "main" form for a pretty large program that has been my project for the last 13 years.  It is on the edge of having more controls than VB6 allows, so I thought perhaps having to declare WV (with events) was pushing it over the limit.  I don't know if it's possible, but *it would be wonderful if we could have an ARRAY of WV (with events)*.  I'm not sure if these declarations "count" towards the VB6 limits or not, but either way, this would allow an array of WV that match an array of PicBoxes that "host" the WVs that I want to use the in program (there are several).  This is exactly how I'm implementing this with the Webbrowser controls that I'm trying to replace.



I wanted to highlight the above, as I believe I have hit the VB6 maximum number of controls for a form.  I was able to save the code (for a while), but then randomly, VB6 started kicking me out of the IDE without warning -- no Save, no nothing.

I currently need 10 WebView controls to replace the webbrowser controls in the form.  They are an array, so it seems to be ok with these, but I will have to see if there's anything that can be deleted from the form in order to truly replace all of them.

I don't have a clue what would go into doing this, but I'd like to think everyone would benefit from it.

Thanks!

----------


## jpbro

> It would be wonderful if we could have an ARRAY of WV (with events)


The RC6.cEventCollection might be what you are looking for. I've adapted Olaf's original demo to show how you can use the cEventCollection with cWebView2 bound to a control array of PictureBoxes:

WebViewEventCollection.zip

The code should be fairly easy to understand on it's own - it's only slightly more complicated that it would be if we the cEventCollection had an Item property, but I've made do with a separate cArrayList to hold WV references that we can access via the cEventCollection Key property). Let me know if you have any questions though.

----------


## BooksRUs

> The RC6.cEventCollection might be what you are looking for. I've adapted Olaf's original demo to show how you can use the cEventCollection with cWebView2 bound to a control array of PictureBoxes:
> 
> WebViewEventCollection.zip
> 
> The code should be fairly easy to understand on it's own - it's only slightly more complicated that it would be if we the cEventCollection had an Item property, but I've made do with a separate cArrayList to hold WV references that we can access via the cEventCollection Key property). Let me know if you have any questions though.


Cool!

I'll check it out and let you know.

Thanks!

----------


## Schmidt

> I currently need 10 WebView controls to replace the webbrowser controls in the form.  
> They are an array, ...


Then the easiest way to keep up with the existing "scheme" would be,
to implement a little "Project-Private-UserControl" for your WebView2-Binding.

E.g. something like that into a UserControl, named *ucWV*:


```
Option Explicit

Event DocumentComplete() 'redefine all the Events you need externally in this place...

Private WithEvents mWV As cWebView2, InitDone As Boolean

Public Property Get WV() As cWebView2
  EnsureBinding
  Set WV = mWV
End Property
 
Private Sub EnsureBinding()
  If Not Ambient.UserMode Then Exit Sub
  If mWV Is Nothing And Not InitDone And Extender.Visible Then
     InitDone = True: Set mWV = New_c.WebView2(UserControl.hWnd)
     UserControl_Resize
  End If
End Sub

Private Sub UserControl_Resize()
  If Not mWV Is Nothing Then mWV.SyncSizeToHostWindow
End Sub

'*** Event-ReDelegation of internal Events (only those which are needed externally)...
Private Sub mWV_DocumentComplete()
  RaiseEvent DocumentComplete 're-raise the internal Event to the outside
End Sub
```

After your Private UC was defined, you can now place two of them on a Form (as a Ctl-Array), then using this Code:


```
Option Explicit
 
Private Sub Form_Load()
  Visible = True 'always ensure Visibility of the TopLevel-Window first

  ucWV(0).WV.NavigateToString "<h1>Hello World</h1>" 'Ctl at Index 0 navigates to a String
  ucWV(1).WV.Navigate "https://google.com" 'Ctl at Index 1 navigates to Google
End Sub

Private Sub ucWV_DocumentComplete(Index As Integer) 'example for Ctl-Array-based Event-Handling
  With ucWV(Index).WV
    Debug.Print .jsProp("Array.from(document.getElementsByTagName('h1')).map(e=>e.innerText).join(',')")
  End With
End Sub
```

So it just boils down to a bit of work inside the UC (for the Event-Definition and -ReDelegation).

Though in the end this should be quite elegant and robust.

Olaf

----------


## BooksRUs

> Then the easiest way to keep up with the existing "scheme" would be,
> to implement a little "Project-Private-UserControl" for your WebView2-Binding.
> 
> E.g. something like that into a UserControl, named *ucWV*:
> 
> 
> ```
> Option Explicit
> 
> ...


Ok, Newbie alert!   :Duck: 

I know this will sound crazy, but I have never created my own control... but, I'm willing to give it a try.

To start, is this an ActiveX DLL, EXE, OCX?

For the events that have parameters, do I have to declare the same parameters in the Event declaration, then pass them "up" to the real control, or do the parameters automatically go up?

Also, I was trying to add a "Busy" flag, as I didn't see how I can do this:
1. Navigate somewhere
2. wait until WV is actually there and complete
3. continue

So, in my main program, I basically set a global Boolean for *each* WV as WVbusy=true, just before I WV.navigate, then in the NavigationCompleted event, I reset the global WVbusy back to false.

Since I'm "extending" the WV, I didn't know how/if I could extend it this way?

Thanks!

----------


## saturnian

I programmed an ocx encapsulating the RC6's Webview2 for my own purposes. It is available* here*, for those interested.


It is a version which will evolve with the improvements of the RC6 and which is delivered as it is, without any guarantee. But in my software, it works perfectly. Thanks again to Olaf!

François

----------


## avinash7

While opening the application for the 1st time after starting computer, application crashes with below details in the event viewer. From 2nd time onwards, no issues at all on same computers. This happens for both installed EXE or running project from VB6 IDE. We have kept 30 seconds timeout for BindTo method (WV.BindTo(picWV.hWnd, 30)). Timeout doesn't seem to be the issue as application crashes immediately. All computers have Evergreeen WebView2-Runtime installed which is updated automatically as well as properly registered required RC6 related DLLs in single folder. This happens on multiple computers. We are opening both EXE as well as VB6 IDE with Run as Administrator, if that matters.

Faulting application name: VB6.EXE, version: 6.0.81.76, time stamp: 0x3592011f
Faulting module name: ntdll.dll, version: 10.0.19041.1566, time stamp: 0xbde09443
Exception code: 0xc0000374
Fault offset: 0x000e6d03
Faulting process id: 0xde4
Faulting application start time: 0x01d83e7836746466
Faulting application path: D:\Program Files (x86)\Microsoft Visual Studio\VB98\VB6.EXE
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: 91d860ff-e220-4c76-b631-9b18f578ba09
Faulting package full name: 
Faulting package-relative application ID:

----------


## Schmidt

> Ok, Newbie alert!  
> 
> I know this will sound crazy, but I have never created my own control... but, I'm willing to give it a try.
> 
> To start, is this an ActiveX DLL, EXE, OCX?


A "Project-Private-UserControl" is "just another module" (in your normal Std-Exe-Project)
You add it in the same way as an additional Form (*.frm), Module (*.bas), Class (*.cls)... 
via Context-Menu in your Project-Tree as a UserControl (ending up with a *.ctl -File in your ProjectTree when saving).




> For the events that have parameters, do I have to declare the same parameters in the Event declaration...?


Yes - and since you have to "Re-Delegate them" anyways (see the last section of my Demo),
you will have to receive them first in the internal EventSink-Handler of the WV.

And once you have that EventHandler selected (via DropDown),
you can immediately copy its "Param Signature" as is - into the Event-Declaration at the Top of your little UC.

Re-Delegating 10 Events or so, should not take more than 5 minutes of "Copy&Paste-work".




> Also, I was trying to add a "Busy" flag, as I didn't see how I can do this:
> 1. Navigate somewhere
> 2. wait until WV is actually there and complete
> 3. continue


Actually, you don't need to implement your own "Wait-Handling" for Navigation... since this is already built-in.
(please look at the optional TimeOut-Param in the Navigate-Methods).

HTH

Olaf

----------


## Schmidt

> While opening the application for the 1st time after starting computer, application crashes


Are you sure that this crash is caused by the WebView2?

What if you take a very simplified example (e.g. similar to the one w.wolff has posted in #148):


```
Option Explicit

Private WithEvents WV As cWebView2

Private Sub Form_Load()
    Visible = True: Caption = "Now navigating to Google..."
    
    Set WV = New_c.WebView2(Me.hWnd)
        WV.Navigate "https://google.com"
End Sub

Private Sub Form_Resize()
    If Not WV Is Nothing Then WV.SyncSizeToHostWindow
End Sub

Private Sub WV_DocumentComplete()
    Caption = "Document complete"
End Sub
```

Put this into a virginal StdExe-Project(-Form) and compile.
Then re-start your machine and check the little Executable, how it behaves "at first Startup, shortly after booting the machine".

If that works, then the error is in all likelihood *not* caused by the WebView2-lib (or the wrapper).

Olaf

----------


## BooksRUs

> I programmed an ocx encapsulating the RC6's Webview2 for my own purposes. It is available* here*, for those interested.
> 
> 
> It is a version which will evolve with the improvements of the RC6 and which is delivered as it is, without any guarantee. But in my software, it works perfectly. Thanks again to Olaf!
> 
> François


Thanks for this!!  I have downloaded and I'm trying it out.  My first problem is how to set it up to call the .JSrun with Parameters?  I'm converting the code from using the WebView2 directly and it's complaining:

*Type Mismatch: array or user-defined type expected*

I have injected a small JS with 2 parameters (user and password), so that I can auto-login to a website.

Thanks!

----------


## BooksRUs

> Re-Delegating 10 Events or so, should not take more than 5 minutes of "Copy&Paste-work".


While this exercise seemed trivial enough, it appears that to provide a true "wrapper" around this with Indexes, I must re-create/declare *ALL* the other Let/Get and Methods for *each* of the properties/methods of the actual WV object.

I did try to do this, but the .jsProp was a little confusing, while most others were straightforward.  I only tried to do the ones that I'm using to change your Demo program to work with 2 of my own ucWV objects (I dynamically Load a 2nd one, just to make sure that I can dynamically Load the object).

----------


## saturnian

> Thanks for this!!  I have downloaded and I'm trying it out.  My first problem is how to set it up to call the .JSrun with Parameters?  I'm converting the code from using the WebView2 directly and it's complaining:
> 
> *Type Mismatch: array or user-defined type expected*
> 
> I have injected a small JS with 2 parameters (user and password), so that I can auto-login to a website.


Have you tried : (where FLogin is the Javascript procedure)


```
    Dim Param_Array(1) As Variant
    Param_Array(0) = "MyUserID"
    Param_Array(1) = "MyPassword"
    OrdoWebView1.jsRun "FLogin", Param_Array()
```

----------


## paliadoyo

I All,

I am not able to use the RC6 WebView2 from outside VB6. In VB6 (in the IDE and compiled) everything works correctly. The same if I use the "saturnian" control (an ocx encapsulating the RC6 WebView2). The problem is when I want to use the WebView2 from, for example, PowerBuilder. I've been using RC without problems in PB for a long time, but I can't get the WebView2 to work. When I call BindTo , the PB IDE crashes (the same in a compiled version) with the same error it gives to "avinash7" (error in ntdll.dll"). 
I have tested the AntView control (https://antview.dev/downloads/) which I believe uses the same mechanism (WebView2Loader.dll) and everything works correctly, both in VB6, PowerBuilder, even in an Excel userForm.
If I use the saturnian control in PowerBuilder, I get the error (just instantiate the control):
Attachment 184685
For what it's worth, in PowerBuilder's object browser, I can see all RC6 classes except "cWebView2":
Attachment 184686
However, the error does not occur when creating the cWebView2 object, but when calling BindTo (or when creating it by passing the hWnd parameter).
Any ideas?

Thanks!

----------


## carl039

@saturnian

Does your ActiveX control allow the setting of the userDataFolder ?
Can't seem to find it in VB6 Object Browser.

Thanks

----------


## saturnian

> @saturnian
> 
> Does your ActiveX control allow the setting of the userDataFolder ?
> Can't seem to find it in VB6 Object Browser.
> 
> Thanks


For the moment no. But if you are using a Fixed Version of WebView2, the user directory data is in the installation folder of this version (by default: C:\ProgramData\OrdoWebView2\Microsoft.WebView2.FixedVersionRuntime\Data\EBWebView)
You can copy the contents of the C:\ProgramData\OrdoWebView2\Microsoft.WebView2.FixedVersionRuntime folder several times and assign a version of the webview2 control to each user by setting the EdgeFixedPath property.
But this cannot be changed on the fly. You must use one OrdoWebView2 control per user, modify the EdgeFixedPath property and launch the Init method.

Best regards

----------


## carl039

> For the moment no. But if you are using a Fixed Version of WebView2, the user directory data is in the installation folder of this version (by default: C:\ProgramData\OrdoWebView2\Microsoft.WebView2.FixedVersionRuntime\Data\EBWebView)
> You can copy the contents of the C:\ProgramData\OrdoWebView2\Microsoft.WebView2.FixedVersionRuntime folder several times and assign a version of the webview2 control to each user by setting the EdgeFixedPath property.
> But this cannot be changed on the fly. You must use one OrdoWebView2 control per user, modify the EdgeFixedPath property and launch the Init method.
> 
> Best regards



Thanks, great job on your control btw.

----------


## carl039

@Olaf

Is there any plans to include all properties as detailed here in particular:

IsPasswordAutosaveEnabled
IsGeneralAutofillEnabled

Thanks

----------


## inspace

just ran across this, it's exactly what i've been looking for, so thank you.

i have a question, hopefully someone can help.

i've figured out mostly everything i need, but i need help with 2 things.

1) outputting the entire html of the website into a textbox. i was able to use WV.jsProp("document.body.innerHTML") but it only captures part of the html, and i need the entire source of the page.

2) scan entire page for elements such as ID, NAME, HREF, and display them in a textbox. basically, with the webbrowser control i would do this:

    For X = 0 To WebBrowser1.Document.All.Length
        strID = WebBrowser1.Document.All.Item(X).Id
        If Not strID = "" Then txtIDs.Text = txtIDs.Text & "(" & X & ") " & wB.Document.All.Item(X).Id & vbNewLine
    Next X

so basically that just loops through every element on the page, checks if it has an ID, and if so it displays it in a textbox. then you can replace Id with name or href. i need to re-create that same thing here. does anyone know how to achieve this? thanks!

----

edit:
i figured out #1 i think. if anyone else is having the same issue, try using WV.jsProp("document.documentElement.outerHTML")

----------


## Schmidt

> 2) scan entire page for elements such as ID, NAME, HREF, and display them in a textbox.


With the WebView2 you should get more familiar with its JS-interface ...
(doing all of the more complex stuff, by adding js-Functions beforehand - and then calling these from VB)

For example, if you add the following js-function (via WV.AddScriptToExecuteOnDocumentCreated):


```
WV.AddScriptToExecuteOnDocumentCreated New_c.ArrayList(vbString, _
   "function getByExpression_id_tag_val_name_href(sExpr){", _
   "    var resArr = []", _
   "    for (var e of document.querySelectorAll(sExpr).values()){", _
   "        resArr.push({id:e.id, tag:e.tagName, val:e.value, name:e.name, href:e.href})", _
   "    }", _
   "    return JSON.stringify(resArr)", _
   "}").Join(vbLf)
```

You can then use this js-routine from VB (with a "Selector-Filter-Expression"-param) e.g. this way:

Debug.Print WV.jsRun("getByExpression_id_tag_val_name_href", "[id]:not([id=''])")

The blue marked Expression-String above, filters for:
- all Elements which contain the ID-attribute (the leading [id] -part)
- and of those with an id-attribute, ignore the ones which have an empty string in it (the not([id=''] -part)

These Selector-Expressions are extremely powerful - just google for examples...

HTH

Olaf

----------


## NemoN

Does anyone have an example of how to use NavigateWithWebResourceRequest with HTTP Basic Auth?

----------


## shahramdelta

Hi everyone

I just wanted to know is there any equivalent method in webview2 for the followings:

suppose mdocDocument is declared as an HTMLDocument

set mhtmInput1 = mdocDocument.createElement("Input")

mdocDocument.appendChild mhtmInput1

set mhtmCoords = mdocDocument.getElementById("coords")

mdocDocument.parentWindow.event

mdocDocument_onClick

mdocDocument.parentWindow.Blur


Thanks in advance

----------


## wwolf

> suppose mdocDocument is declared as an HTMLDocument


The HTMLDocument and the corresponding interface do not exist here. You have to program this code (a function) in JavaScript and either integrate it statically into the page or add it dynamically via VB. You can call the function from your programme at any time (also parameterised). See also: AddScriptToExecuteOnDocumentCreated, jsRun, jsRunAsync and ExecuteScript.

----------


## Meierk

Hi Olaf
The problem "Runtime Error 53: Error in FindFirstFile: ErrNum: 3, The system cannot find the path specified." persists. 

I had to clean install my windows 10, registered RC6.dll and today installed WebView2. WebView version 103.0.1264.71 installed into the folder "C:\Program Files (x86)\Microsoft\EDGE\Application", your program looks for the "EdgeWebView" folder. 

Solution? Should I rename this folder?

Regards

----------


## Meierk

Hi Olaf
Solutions sometimes can be quick: I did what I should have done before posting. 

I copied the "Edge" folder and renamed the copy "EdgeWebView" - now my program runs smooth!

Regards

----------


## lodep

Hi !

Thank you for this great tool !
I am looking for a way to change the WebView2 default User-Agent.
I know that I can send a request with NavigateWithWebResourceRequest and set the User-Agent via the headers but I need that all the resources of the page are loaded with the same User Agent. In .net the solution is to call this method :

var settings = new Web.CoreWebView2.Settings;
settings.UserAgent = "XXXXX";

Is there a way to do this ?

----------


## Schmidt

> I need that all the resources of the page are loaded with the same User Agent...


There's a ton of settings possible via optional commandline-string (which you can pass along in the Bind-Method) -
"--user-agent ..." just being one of them...
https://peter.sh/experiments/chromiu...es/#user-agent 

I'd try it this way first...

HTH

Olaf

----------


## lodep

> There's a ton of settings possible via optional commandline-string (which you can pass along in the Bind-Method) -
> "--user-agent ..." just being one of them...
> https://peter.sh/experiments/chromiu...es/#user-agent 
> 
> I'd try it this way first...
> 
> HTH
> 
> Olaf


How can I say... JUST A HUGE *THANK YOU* !!!
This is just amazing, it works !
Thank you  :Smilie:

----------


## lodep

Hi @Olaf,

One more question : I can't access the documenturl property sometimes (it's blank).
I've read in previous posts that you have a workaround for this problem and that you'll need to update the DLL.
Is it possible to access this property with a temp fix using JSPROP for example ?

Thanks,

----------


## jenniger9

can anybody share with me how to get webview2 cookies vb6

----------


## Schmidt

> can anybody share with me how to get webview2 cookies vb6


Please study (or at least search through) the postings of the discussion-thread you're currently in...
Cookie-retrieval was already a topic here in: https://www.vbforums.com/showthread....=1#post5498591

Olaf

----------


## sergeos

Can this tool(webview2) replace selenium to emulate user behavior on the webpage?

----------


## Schmidt

> Can this tool(webview2) replace selenium to emulate user behavior on the webpage?


In my understanding, Selenium was written as a generic Test-Tool which can "work against multiple Browser-engines".

The WebView2 is just an encapsulation of a single Browser-engine (chromium) -
minus the additional "generic Automation- and Test-interfaces".

So, if you currently use Selenium for your own testing-purposes with success,
why change it to something "less capable" and "less generic".

Just my $0.02...

Olaf

----------


## jangle

Hello!
Can you explain how to save downloaded web page to local disk?

----------


## sergeos

> In my understanding, Selenium was written as a generic Test-Tool which can "work against multiple Browser-engines".
> 
> The WebView2 is just an encapsulation of a single Browser-engine (chromium) -
> minus the additional "generic Automation- and Test-interfaces".
> 
> So, if you currently use Selenium for your own testing-purposes with success,
> why change it to something "less capable" and "less generic".
> 
> Just my $0.02...
> ...


no, I don't use selenium. but I have seen how it works. The problem is that with every update of firefox, you need to change the version of the woking executable to connect firefox to the web page.
I also join the question above regarding use cases.

----------


## Schmidt

> Hello!
> Can you explain how to save downloaded web page to local disk?


Not sure, what is meant here... 
(there is an interactive right-mouseclick-context-menu in the chromium-engine, 
which allows to trigger "Save as..."-commands).

If it's only "plain-text-" or "plain-binary"-saving of a given URL -
then a better suited (more lightweight) helper-object is available via the winhttp 5.1 reference...

Olaf

----------


## jangle

> Not sure, what is meant here... 
> (there is an interactive right-mouseclick-context-menu in the chromium-engine, 
> which allows to trigger "Save as..."-commands).
> 
> If it's only "plain-text-" or "plain-binary"-saving of a given URL -
> then a better suited (more lightweight) helper-object is available via the winhttp 5.1 reference...
> Olaf


I have a list of about 100 web pages. I need to automatically download them and save them along with the pictures to a local disk. 
Can I use this component for this task or should I use something else?

----------


## Resurrected

Olaf:

I was using RC6 version: 6.0.0.9, everything is fine.
Then I upgraded to RC6 version: 6.0.0.10, my program broke. 

It was broken when this line of code stopped returning anything:


```
WV.jsProp("document.querySelector('input').value")
```

I have to switch back to 6.0.0.9 and my program works again.

I notice there are some new features added to cWebView2, perhaps that's where the root of the problem is.

----------


## Schmidt

> Olaf:
> 
> I was using RC6 version: 6.0.0.9, everything is fine.
> Then I upgraded to RC6 version: 6.0.0.10, my program broke. 
> 
> It was broken when this line of code stopped returning anything:
> 
> 
> ```
> ...


Had to adapt the jsProp-Resolver Method internally (in 6.0.10) due to "security-reasons" -
(the old version was using eval(...) to resolve the jsProp-expression, and that does not work in all cases).

What the new version still supports, is "nested Prop-Expressions" - as for example:
Debug.Print WV.jsProp("window.document.title")

But please note, that the above "nested expression" does not contain any parentheses (which indicate function-calls).
So, it has to be "pure properties" now (since I'm not using eval anymore for jsProp-evaluation internally).

To solve your problem, just add a little helper-function like e.g:
WV.AddScriptToExecuteOnDocumentCreated "function getQSValue(qsExpr){return document.querySelector(qsExpr).value}"
...before loading a document.

This will allow you, to use WV.jsRun(...) instead, to get your values:
Debug.Print WV.jsRun("getQSValue", "input")

HTH

Olaf

----------


## BooksRUs

> Re-Delegating 10 Events or so, should not take more than 5 minutes of "Copy&Paste-work".





> While this exercise seemed trivial enough, it appears that to provide a true "wrapper" around this with Indexes, I must re-create/declare *ALL* the other Let/Get and Methods for *each* of the properties/methods of the actual WV object.
> 
> I did try to do this, but the .jsProp was a little confusing, while most others were straightforward.  I only tried to do the ones that I'm using to change your Demo program to work with 2 of my own ucWV objects (I dynamically Load a 2nd one, just to make sure that I can dynamically Load the object).



I just wanted to BUMP this response again to see if anyone else has successfully tried/done this (making a User Control with WV so that we can have indexed UC with multiple on one form)?

I want to replace about 17 old webbrowser controls in my VB6 program and the form has simply run out of available controls (I guess 256 is the VB6 limit).  Most, if not all of them, are "hosted" on a vbalDTabControl (from vbAccelerator.com), which allows me to just set the "panel" property directly to the ucWV (user control WebView) that I created.

The code seems to actually run fine, but only first WV created actually renders anything.  The rest look like they are working correctly "under the hood" (when debugging, all events are fired), but only a blue box is rendered on the screen.

Any help would be appreciated.

Thanks for a great control!

----------


## Resurrected

> Had to adapt the jsProp-Resolver Method internally (in 6.0.10) due to "security-reasons" -
> (the old version was using eval(...) to resolve the jsProp-expression, and that does not work in all cases).
> 
> What the new version still supports, is "nested Prop-Expressions" - as for example:
> Debug.Print WV.jsProp("window.document.title")
> 
> But please note, that the above "nested expression" does not contain any parentheses (which indicate function-calls).
> So, it has to be "pure properties" now (since I'm not using eval anymore for jsProp-evaluation internally).
> 
> ...


Olaf, thanks for the reply. I will make changes to my code.

Thanks again for your support in all those in years.

----------


## Resurrected

Olaf,

Another problem related to .jsRun method.

It seems that .jsRun returns the previous result if the current result is undefined? 

For example, 

.jsRun(js1) returns 'result of js1' if js1 works.
.jsRun(js2) returns also 'result of js1' if js2 failed.
.jsRun(js3) returns 'result of js3' if js3 works.

I was assuming that .jsRun would return something like NULL when the script fails.

Is there any possible mistake on my side? Or is there anything I don't know about .jsRun?

Thanks

----------


## Schmidt

> It seems that .jsRun returns the previous result if the current result is undefined? 
> 
> For example, 
> 
> .jsRun(js1) returns 'result of js1' if js1 works.
> .jsRun(js2) returns also 'result of js1' if js2 failed.
> .jsRun(js3) returns 'result of js3' if js3 works.
> 
> I was assuming that .jsRun would return something like NULL when the script fails.


I've fixed that now - returning Empty in case of a js-error (a returned js-*null*-value maps to VT_Empty in the COM-world).
 Have not compiled and re-uploaded yet, but it will come in the next release...

In the interim you have two ways to workaround that:
1) via your own try-catch-block within your self-defined js-Function (to return a null, or an err-string in case of an error)
2) or relying on the existing, internal "try-catch"-mechanism of jsRun/jsProp
.. (which in case of 2) manifests itself in: WV.jsLastError

So, for "critical js-Calls that might fail" (and have no internal try/catch definition),
you can always add an additional line after the WV.jsRun(...) like:
If Len(WV.jsLastError) Then LogOrRaiseThe WV.jsLastError

Olaf

----------


## paliadoyo

I Olaf.
Do you know why I can't see (and use) the cWebView2 class in Excel?
Attachment 185944
The same happens in other languages (powerbuilder for example), where I have had no problems using other RC6 classes


Regards

----------


## BilalAhmed

Hello Olaf,

First of all thank you very much for a wonderful contribution!!!

Couple of problems I am having:

1. browser.jsProp("document.getElementById('divid').innerHTML") never returns any thing. However browser.jsProp("document.documentElement.innerHTML") returns whole document html and I then have to parse through whole document to find content which I am looking for.

2. Below is my JS Code
var url = 'https://abc.com/page1';
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('accept', 'application/json, text/plain, */*');
xhr.setRequestHeader('Authorization', 'token');
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('content-length', '0');
xhr.setRequestHeader('Accept-Language', 'en-US,en;q=0.9');
xhr.setRequestHeader('content-type', 'application/json');

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      ret = xhr.responseText; document.getElementById('dvRes').innerHtml = xhr.responseText;
   }};
var data = '';
xhr.send(data);

so when I first time do browser.ExecuteScript(MyJSCode) it works well and sets output to the specified div. But, If I have to make another xhr call or even more calls, it never even attempts to make a call (I also check network calls from Dev Tools window). So in a nutshell, it makes only one xhr call and then never goes for 2nd or 3rd one.

Any help or direct guidance will be highly appreciated!!!

Thank you!

----------


## Schmidt

Just a few posts above (in #186) both your questions were answered.

Your second question "indirectly" - meaning:
- encapsulate the remote-call in a proper js-helper-function 
..e.g. called function RPC(URL, oData){...}
- then add this function using: WV.AddScriptToExecuteOnDocumentCreated <your js-function-string>
- then you can use this function via WV.jsRun("RPC", ...)

Olaf

----------


## talatoncu

Dear Olaf,

I have been using Webview2-binding for a long time. Thank you very much for your valuable creation of this library. 

After I have downloaded and installed "The vbRichClient-Framework (currently at Version 6.0.10", I am in great trouble.

Although Webview2 perfectly loads the document in the picturebox, in the NavigationCompleted event,  IsSuccess is always false while WebErrorStatus=0.

Am I doing something wrong or something has been chaned that I don't know.

Thank you very much for your assistance.

----------


## Schmidt

> After I have downloaded and installed "The vbRichClient-Framework (currently at Version 6.0.10", I am in great trouble.
> 
> Although Webview2 perfectly loads the document in the picturebox, in the NavigationCompleted event,  IsSuccess is always false while WebErrorStatus=0.
> 
> Am I doing something wrong or something has been chaned that I don't know.


Have just tested this with a WV.Navigate to "https://google.com" - 
and the incoming NavigationCompleted-EventParams are: IsSuccess=True, WebErrorStatus=0

In the MS-documentation for the IsSuccess-Param is stated:
_...Note that WebView2 will report the navigation as 'unsuccessful' if the  load for the navigation did not reach the expected completion for any  reason. Such reasons include potentially catastrophic issues such  network and certificate issues, but can also be the result of intended  actions such as the app canceling a navigation or navigating away before  the original navigation completed. Applications should not just rely on  this flag, but also consider the reported WebErrorStatus to determine  whether the failure is indeed catastrophic in their context.

_So, maybe the site you navigate to has an outdated certificate - or undergoes several redirects?

Olaf

----------


## shamiur

Hi Olaf,

RC6 Version 6.0.10 does not return values for html textbox on vb form. It does the same thing for WebView2Demo example as well.
MsgBox WV.jsProp("document.getElementById('txt1').value")

Kind Regards,

----------


## talatoncu

> Have just tested this with a WV.Navigate to "https://google.com" - 
> and the incoming NavigationCompleted-EventParams are: IsSuccess=True, WebErrorStatus=0
> 
> In the MS-documentation for the IsSuccess-Param is stated:
> _...Note that WebView2 will report the navigation as 'unsuccessful' if the  load for the navigation did not reach the expected completion for any  reason. Such reasons include potentially catastrophic issues such  network and certificate issues, but can also be the result of intended  actions such as the app canceling a navigation or navigating away before  the original navigation completed. Applications should not just rely on  this flag, but also consider the reported WebErrorStatus to determine  whether the failure is indeed catastrophic in their context.
> 
> _So, maybe the site you navigate to has an outdated certificate - or undergoes several redirects?
> 
> Olaf


Dear Olaf,

Thank you very much for your valuable explanation.

So, I think the best thing is to "...consider the reported WebErrorStatus to determine  whether the failure is indeed catastrophic in their context...".

----------


## Schmidt

> RC6 Version 6.0.10 does not return values for html textbox on vb form. It does the same thing for WebView2Demo example as well.
> MsgBox WV.jsProp("document.getElementById('txt1').value")


I've explained why this happens - and also a workaround for it - in post #186 above.

Olaf

----------


## Bob17

Hi Olaf,
is it possible that you offer some sort of error number or exception on calling BindTo method instead of just returning 0 or 1? I have a case of a shutdown of msedgewebview2.exe(s) after they initialize and after they create files/folders in the given user data folder. They just shut down very shortly after starting and the return value of BindTo is 0. I tried every suggestion from WebView2 forums without success, there is no trace of it in event logs, I have no idea how to proceed. I saw that .NET WebView2 library in such situations does return exceptions with meaningful messages, it would be great if you could offer similar information on BindTo errors, thanks.

----------


## Resurrected

Olaf

I'm experiencing a problem.

Today, out of nowhere my program suddenly ran into "couldn't initialize Webview2 binding" on startup.
The problem remains after I tried rebooting my pc, recompliling the exe, reinstalling webview2 runtime, running in the IDE, or reresgistering RC6 binaries.

On another PC of mine, there is no problem.

----------


## Schmidt

> Today, out of nowhere my program suddenly ran into "couldn't initialize Webview2 binding" on startup.
> The problem remains after I tried rebooting my pc, recompliling the exe, 
> reinstalling webview2 runtime, running in the IDE, or reresgistering RC6 binaries.


Cannot reproduce the behaviour on my machine - 
but nevertheless have uploaded a new RC6-BaseLibs-package - 
which now contains the newest version of the MS 'WebView2Loader.dll' -
as well as a slightly changed BindTo-Method, which deals more thouroughly with "compatible-versions"...

Please check it out after downloading the new package (with all Dlls) - 
and re-registering RC6.dll

@Bob17
This might help also in your case - though not sure (it's still a "shot into the blue" - 
because - as said - cannot reproduce the behaviour).

What helped me in this regard (in the early phases of developing it) was, 
to delete the "UserFolder" completely (in case you gave it a specific location) -
or to change the location to a different UserFolder-Path with "full write-rights, and nothing else in it".

HTH

Olaf

----------


## Resurrected

Olaf

I'm sorry to say that after registering the new DLLs, the problem remains the same: "couldn't initialize WebView-Binding".

I'm running the Webview2Demo project.

I'm starting to doubt if it's a Win7 thing. Just recently I constantly get notification from Chrome that it will not be updated in Win7 Os.

----------


## Resurrected

There is a fixed version Webview2 for downloading. Is it possible to test against this?

----------


## Schmidt

> There is a fixed version Webview2 for downloading. Is it possible to test against this?


Sure, the first optional Param of the BindTo-Method allows that.

But I'd make sure, that you point it to a (lower) version of MS-Edge, which is still supported by Win7.

Olaf

----------


## Resurrected

Olaf

Good news.

By changing the browserInstallPath of the BindTo method, I've come to the results:

Microsoft.WebView2.FixedVersionRuntime.108.0.1462.46.x64 > couldn't initialize WebView-Binding
Microsoft.WebView2.FixedVersionRuntime.107.0.1418.62.x64 > No errors.

I'm running Win7 Os.

Regards

----------


## Bob17

Hi Olaf,
Calling a vb6 COM dll that has RC6 WebView2 from a .NET application crashes the process (on calling BindTo method) with heap corruption error in ntdll.dll. This is reproducible, I have attached sample code with one c# forms project and one vb6 dll project. Could you please take a look and give some comments on it, maybe you can pinpoint the cause. Thanks!

----------


## Schmidt

> Hi Olaf,
> Calling a vb6 COM dll that has RC6 WebView2 from a .NET application crashes the process...


I'm aware of that problem - 
and .NET-compiled (32Bit-x86) Host-Processes are not the only ones who cause it...
There's also VBA (when run from within 32Bit Excel or Access.exe Processes) which has that problem.

I have currently not investigated this deeply - but my assumption is, 
that a VB6-compiled 32Bit Host-Exe is initializing the vb6-runtime-dll differently on startup -
(compared to an "isolatedly loaded" VB6-COM-Dll - like the RC6 on different "Host-Exes").

In case of a VB6-compiled Host-exe the RC6-Dll "meets an already initialized vb6-runtime" (on the MainThread) -
and in case of differently compiled Host-exes, the RC6-Dll "has to initialize the vb6-runtime itself".

There is all sorts of other (threading-related things) to consider along with that - 
it might be that the hosting Executables where it fails, have initialized their COM(Threads) to "MTA-mode" and not "STA-Mode".

I hesitate to invest much of my time into it - because TwinBasic offers a WebView2-Binding as well (also for VBA).
And ".NETers" have also their own "WebView2-Binding" available in a .NET-based Class-wrapper.

Is there a reason, why you want to use (32Bit only!)-VB6-compiled-COM-Dlls in a .NET-App?

Olaf

----------


## Bob17

Well, I need to support such scenario where web browsing is in the COM dll and the caller is arbitrary application, possibly .NET-based. One interesting detail, if .NET app is based on Framework 3.5 or 4 then the app is not crashing!

----------


## Schmidt

> Well, I need to support such scenario where web browsing is in the COM dll and the caller is arbitrary application, possibly .NET-based. One interesting detail, if .NET app is based on Framework 3.5 or 4 then the app is not crashing!


A VB6-Host-Exe might help (which encapsulates the whole thing - including the VB6-Form you "BindTo").

You can even make this VB6-Executable an ActiveX-Exe-Project -
with your current "Dll-based Public COM-Class" exposed as a Public Class of the AciveX-Exe -
which is BTW one of the few ways, to make a VB6-Class "consumable" also by *64Bit*-Host-Processes.
(remember, you cannot load a VB6-compiled 32Bit COM-Dll into a 64Bit-Process *directly* - 
only *Cross*-*Process*-COM-calls between 64Bit-Consumer-Process and a 32Bit-ClassHost-Process allow that feat)

Olaf

----------


## paliadoyo

> I'm aware of that problem - 
> and .NET-compiled (32Bit-x86) Host-Processes are not the only ones who cause it...
> There's also VBA (when run from within 32Bit Excel or Access.exe Processes) which has that problem.
> 
> I have currently not investigated this deeply - but my assumption is, 
> that a VB6-compiled 32Bit Host-Exe is initializing the vb6-runtime-dll differently on startup -
> (compared to an "isolatedly loaded" VB6-COM-Dll - like the RC6 on different "Host-Exes").
> 
> In case of a VB6-compiled Host-exe the RC6-Dll "meets an already initialized vb6-runtime" (on the MainThread) -
> ...


Hello Olaf. You are right. By creating an ActiveX-Exe and exposing a cWebView2 wrapper as a public class of the ActiveX-exe I can use WebView2 in my PowerBuilder application without problems (something that directly using RC6 I have not achieved). Not ideal, but at least I have a choice.

Thank you very much!

----------


## darjeeling

Hi,
I have the same problem as Resurrected.
So Resurrected seems to solve with 'Microsoft.WebView2.FixedVersionRuntime.107.0.1418.62.x64' but i have not found the installer of this version.
Microsoft publish the latest version only.
Anybody can help me ?

----------


## Schmidt

The download for fixed versions is at the bottom-right-corner of this page:
https://developer.microsoft.com/en-u...edge/webview2/

Olaf

----------


## darjeeling

Hi Olaf,
Yes i see but it is a CAB.
How to install or use this one ? I'm lost.

----------


## Schmidt

> ...but it is a CAB.


Win10 has direct support for unpacking of *.cab-Archives - 
otherwise use 7zip?

In any case, you should end up with an unpacked Folder, named:
..\Microsoft.WebView2.FixedVersionRuntime.107.0.1418.62.x86
somewhere on your local harddisk.

Now move that whole Folder to a place you prefer in your filesystem -
and then point the 3rd Param of the BindTo-method to that Directory-Path-(String).

Olaf

----------


## darjeeling

Ok Olaf,
Thank you very much and Merry Christmas !

----------


## EasyOneX

Hello.

Is there a project / template for this so that the WebView2 can also be used as an HTML editor?

Thank you very much and Merry Christmas!

Andreas

----------


## Schmidt

> Is there a project / template for this so that the WebView2 can also be used as an HTML editor?


Sure ... did you ever try-out: 
WV.OpenDevToolsWindow
... after a successful WV.BindTo(...) call?

It's (in the meantime) a full-blown IDE-environment with live-changes in the "View",
as soon as you edit and save *.html and *.css files 
(also including support for *.js-Debugging of course).

The DevTools-Window is highly configurable (just play around with it for a day or two) -
and it allows write-interaction with the local FileSystem, once you specify a "trusted root-folder"
(which is usually the root-folder of your "localhost" Webserver-instance - be that NodeJs or IIS or Nginx).

Olaf

----------


## darjeeling

Hi Olaf,
My tests:

1 - Windows 7
MicrosoftEdgeWebView2RuntimeInstallerX86 installed on Windows 7.

First try:
WV.BindTo(picWV.hWnd) => "couldn't initialize WebView-Binding"

Second try:
...
P = WV.GetMostRecentInstallPath
(_WV.GetMostRecentInstallPath seems to be the right path_)
WV.BindTo(picWV.hWnd), , P) => Crash of VB6

and again...
WV.BindTo(picWV.hWnd) => OK it works


2 - Windows 10
No problem it works at anytime !

A solution for Windows 7 ?

----------


## Schmidt

> P = WV.GetMostRecentInstallPath


GetMostRecentInstallPath gives the path to the "Evergreen-Version" (which the "normal" MS-installer is for).

If you want to work against an older "Fixed-Version" (like the one in your *.cab-download),
you have to set:

 P = "C:\some\path\to\my\unpacked\Microsoft.WebView2.FixedVersionRuntime.107.0.1418.62.x86"

and pass that P-StringVariable into the Bind-call.

Olaf

----------


## darjeeling

Hi Olaf,
Thank you i'll try.

Regards

----------


## Adebiyi24

Hello
I tested the demo under w7 but I'm getting this error

----------


## Schmidt

> Hello
> I tested the demo under w7 but I'm getting this error


The reason for this was mentioned a few times already in this Codebank-Thread.
(the Event-interface was changed slightly in newer RC6-versions).

Just comment out the Event-Handler you're having problems with completely -
and then "re-select" the EventHandler from the DropDown-ComboBox at the TopRight of the IDEs CodeEditor
(in case you need this specific Event at all)...

I've not yet uploaded a new Demo-Zip, because the cWebView2.cls is still getting enhancements -
and is not yet "entirely finalized" (COM-interface-wise)... 
I'll always try my best though, to not break the stuff which is currently "in use and established"...

Olaf

----------


## Schmidt

@paliadoyo, Bob17, Resurrected 
...or anybody else who previously had problems with loading WebView2 in "other Host-Processes" like:
Excel(32Bit), .NET(32Bit), Powerbuilder(32Bit)

I think I've found (and fixed) something over the Holidays regarding "more robust BindTo/Loading" ...
Please download RC6 version 6.0.12 from the usual place and check with that (after re-registering).

Olaf

----------


## darjeeling

Hi Olaf,
RC6 version 6.0.12: 
RC6BaseDlls.zip -> HTTP Error 404.0 - Not Found

Regards

----------


## Schmidt

> Hi Olaf,
> RC6 version 6.0.12: 
> RC6BaseDlls.zip -> HTTP Error 404.0 - Not Found


Oops, messed up my FTP-Upload - please try again...

Olaf

----------


## darjeeling

Hi again,

If WV.BindTo(picWV.hWnd) = 0 Then MsgBox "couldn't initialize WebView-Binding": Exit Sub

Sorry but the same problem remain: "couldn't initialize WebView-Binding"

Regards

----------


## darjeeling

Hi again,
I tested several solutions under Windows 7 but without success.
I confirm that I have no problem under Windows 10.
On the other hand, the source code of Wolf (http://www.ww-a.de/download/WebView2-Demo.zip) works perfectly on Windows 7. However, I could not reproduce the 'BinTo' method of Wolf.
I am disappointed.

Regards

----------


## Schmidt

> ...the source code of Wolf (http://www.ww-a.de/download/WebView2-Demo.zip) works perfectly on Windows 7.


If Wolfgangs code is working (in your VB6-*IDE* on *Win7*) - 
then you're doing something wrong in your "init-sequence"...

Here's a minimal Demo-Code for an empty Project with a Form1 (and a reference to RC6)


```
Option Explicit

Private WithEvents WV As cWebView2

Private Sub Form_Load()
  Me.Caption = New_c.Version 'just to check, which RC6-Version is in use...
  
  Me.Visible = True 'the FormOrPicBox.hWnd needs to be Visible, before the BindTo-call
  
  Set WV = New_c.WebView2
  If WV.BindTo(Me.hWnd) Then
     WV.Navigate "https://google.com"
  Else
     MsgBox "Couldn't bind the WebView to the Form.hWnd"
  End If
End Sub

Private Sub Form_Resize() 'ensure full coverage of the Containers ClientArea with the WebView
  If Not WV Is Nothing Then WV.SyncSizeToHostWindow
End Sub
```

HTH

Olaf

----------


## darjeeling

Olaf thank you very much for trying to help me but it still doesn't work.
I have checked the registry keys (HKLM and HKCU) concerning the runtime and tried different versions of this runtime but nothing changes.
I will resolve to use it under Windows 10 even if I hate Windows 10....

----------


## paliadoyo

It works like a charm!
As always, thank you very much for your interest and effort in solving our problems.

Regards

----------


## darjeeling

Hi Olaf,
Good news !
Now it works fine on Windows 7.



```
Option Explicit
Private Cairo As cCairo
Private WithEvents WV As cWebView2

Private Sub Form_Load()
    Me.Visible = True
    Set Cairo = New_c.Cairo
    Set WV = New_c.WebView2
    Cairo.SetDPIAwareness
    If WV.BindTo(Me.hWnd) = 1 Then
        Me.Caption = "INIT OK"
        WV.Navigate "https://google.com"
    Else
        MsgBox "Couldn't bind the WebView to the Form.hWnd"
    End If
End Sub

Private Sub Form_Resize() 'ensure full coverage of the Containers ClientArea with the WebView
  If Not WV Is Nothing Then WV.SyncSizeToHostWindow
End Sub
```

----------


## Bob17

Hi Olaf, 
I wanted to test your BindTo improvements but the vbrichclient.com is having some error 500 problems.

----------


## SearchingDataOnly

> Hi Olaf, 
> I wanted to test your BindTo improvements but the vbrichclient.com is having some error 500 problems.


Microsoft seems to be forcing everything related to *IE* to be removed from the browser, and I don't know if the recent frequent failures (inability to download files) of vbrichclient.com  are related to Olaf's use of *IIS*.

----------


## jpbro

> Microsoft seems to be forcing everything related to *IE* to be removed from the browser, and I don't know if the recent frequent failures (inability to download files) of vbrichclient.com  are related to Olaf's use of *IIS*.


Site was just down due to mystery server reasons....it looks like it's back up now. Maybe Olaf should have used Nginx :P

----------


## SearchingDataOnly

> Maybe Olaf should have used Nginx :P


Yes, Nginx + VbFcgi is much better than IIS.

----------

