Why my coreWebView2 which is object of webView2 is null?
Asked Answered
C

17

23

I am creating a object of Microsoft.Web.WebView2.WinForm.WebView2 but the sub obect of this coreWebView2 is null

Microsoft.Web.WebView2.WinForm.WebView2 webView = new Microsoft.Web.WebView2.WinForm.WebView2()
// Change some GUI properties of webView
webView.CoreWebView.NavigateUrl(url)
// I can not access the above line because CoreWebView is null
Contuse answered 27/7, 2020 at 13:46 Comment(0)
G
18

Use the EnsureCoreWebView2Async method to initialize the underlying CoreWebView2 property. This is documented on MSDN. This property is null on initialization of the WebView2 class object.

CoreWebView2 The underlying CoreWebView2.

public CoreWebView2 CoreWebView2

Use this property to perform more operations on the WebView2 content than is exposed on the WebView2. This value is null until it is initialized. You can force the underlying CoreWebView2 to initialize via the InitializeAsync (EnsureCoreWebView2Async - apparently Microsoft failed to update their documentation) method.

Source (https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winforms/0-9-515/microsoft-web-webview2-winforms-webview2)

Genethlialogy answered 27/7, 2020 at 13:51 Comment(9)
InitializeAsync was renamed to EnsureCoreWebView2Async.Wrecker
I call this method webView.EnsureCoreWebView2Async() but this not work.Still i getting CoreWebView2 property nullContuse
@AbbasTambawala Are you using await? It's an async method. You have to use await to make sure the method completes before moving on to the next portion of your code.Genethlialogy
When I tried to use await it gives an error BadImageFormatExceptionContuse
public async void NavigateTo(string url) { await webView.EnsureCoreWebView2Async(); webView.Source = new Uri(url); }Contuse
@AbbasTambawala Make it public async Task NavigateTo(string url)Genethlialogy
Thanks for helping. With use of public async Task NavigateTo(string url) error is gone but may be EnsureCoreWebView2Async is gone into infinite loop because in this method the second statement ` webView.Source = new Uri(url); ` will not work the method call is terminate after the await webView.EnsureCoreWebView2Async(); statement.an other statements of this function will never be calledContuse
okk thank you for helping me it is because prefer 32 bit is uncheckedContuse
@AbbasTambawala, I am getting the same error "BadImageFormatException" when I use await. is there any solution for this ?Campanile
C
12

I tried everything from all over the web, but CoreWebView2 was always null.

Turns out, I was missing the runtime for Edge.

Then I installed it using the Evergreen Standalone installer from Microsoft Edge WebView2. And then it worked!

Cryohydrate answered 16/3, 2021 at 12:39 Comment(0)
N
11

You can use EnsureCoreWebView2Async to make sure the object is initialized before doing any navigations. However, even easier, you can set the Source property which make sure the initialization is triggered, if not already:

Microsoft.Web.WebView2.WinForm.WebView2 webView = new Microsoft.Web.WebView2.WinForm.WebView2();
webView.Soure = url;
Nostrum answered 27/7, 2020 at 18:8 Comment(1)
When i am trying to change webView.Source it give an exception "Null Reference Exception"Contuse
H
6

Use webView2.EnsureCoreWebView2Async(); at the start of program to initialize and create the event to check if it is initialized or not.

bool ensure = false;

private void webView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
{
    ensure = true;
}

Working demo: https://www.youtube.com/watch?v=S6Zr5T9UXUk

Heder answered 2/4, 2022 at 8:14 Comment(0)
H
5

First you have to initialize webview2 using the following code.

WebView21.EnsureCoreWebView2Async()

Then you should write the following code in the event named CoreWebView2InitializationCompleted.

WebView21.CoreWebView2.Navigate(yoururl)
Hyperaesthesia answered 31/7, 2021 at 21:42 Comment(1)
I had to subscribe to the event before calling "EnsureCoreWebView2Async". Otherwise the CoreWebView2InitializationCompleted event isn't called.Mouse
D
3
    private async void Form1_Load(object sender, EventArgs e)
    {
        await webView2.EnsureCoreWebView2Async();
        webView2.CoreWebView2.Settings.IsStatusBarEnabled = false;
        webView2.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;

        webView2.Source = new Uri("https://someurl.com/");
    }
Delora answered 11/1, 2022 at 13:39 Comment(0)
M
2

In my case, the BadImageFormatException was due to PlatformTarget x86. After changing it to AnyCPU or x64, await webView.EnsureCoreWebView2Async(null); should work, and then webView.CoreWebView should also be non-null.

Manas answered 19/7, 2022 at 8:25 Comment(0)
K
2

Confusingly, if anything goes wrong as part of the CoreWebView2 initialization, EnsureCoreWebView2Async() will return as normal and the CoreWebView2InitializationCompleted event will still fire, seemingly as if initialization succeeded, but CoreWebView2 will be null. We have to check CoreWebView2InitializedEventArgs.Exception in a CoreWebView2InitializationCompleted event handler to see what, if anything, went wrong:

public MainWindow()
{
    this.InitializeComponent();
    // Use the callback instead of awaiting Ensure... because the callback's args.Exception
    // tells us if something went wrong initializing the CoreWebView2
    this.MyWebView.CoreWebView2Initialized += MyWebView_CoreWebView2Initialized;
    MyWebView.EnsureCoreWebView2Async();
}

private void MyWebView_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
    if (args.Exception != null)
    {
        LogHelper.Error("CoreWebView2 initialization failed", args.Exception);
    }
    else
    {
        InitializeMyWebView2();
    }
}
Kluge answered 13/6, 2023 at 13:4 Comment(0)
C
1

As @Abbas Tambawala said in a comment, you have to make sure that your project is set for a specific bitness. The sometimes default "AnyCPU" setting will seem to work but the control won't initialize, await webView.EnsureCoreWebView2Async will return a Task that never completes, CoreWebView2 will be null, and other symptoms will be a clue to check that setting in your project.

Also, be aware that if you are working on a solution with multiple projects, like I was... you need to make sure all the projects are consistently flagged correctly.

The DLL project I was working on was marked as X86, but the project that loaded my DLL was marked with "AnyCPU". Many moments of WTF is going on... the comment about "prefer 32 bit" to Ryan's answer gave the "Ah-HA" moment.

Also, you may want to check what event or method you are setting webView2.Source or calling EnsureCoreWebView2Async in... webView2 needs the UI thread to be completely initialized and the form shown. I generally put my webView2 init code in the Form.Shown event. Here is a link describing the Form Events order: MS-Docs Form Events

Cratch answered 10/12, 2020 at 21:16 Comment(0)
C
1

I got around this issue in my visual basic project by setting a boolean variable in the WebView2.CoreWebView2Ready event then had called a one off do events loop to wait in the forms activated event to check the variable to make sure it was initialized and ready to use

I noticed even after the await Async it was still not ready to use immediately and corewebview2 remained null but this might be a vb thing

Here's an Example converted to c# from my webview2 visual basic project it should work in c#

class SurroundingClass
{
    private bool FstRun = true;
    private bool WebReady = false;

    private void Form1_Activated(object sender, EventArgs e)
    {
        if (FstRun == true)
        {
            FstRun = false;
            InitAsync();
            Wait();  // wait for webview to initiaise
           // code or sub here to reference the control navigate ect
        }
    }
    private void WebView21_CoreWebView2Ready(object sender, EventArgs e)
    {
        WebReady = true;
    }

    private async void InitAsync()
    {
        await WebView21.EnsureCoreWebView2Async;
    }

    private void Wait()
    {
        while (!WebReady == true)
            System.Windows.Forms.Application.DoEvents();
    }
}
Chanel answered 29/12, 2020 at 15:55 Comment(1)
For me the await webView.EnsureCoreWebView2Async will actually return a Task that completes Just not immediately. If i just assume its ready to use and use the form Shown event to initialize and then navigate after the await I don't get a null exception but it doesn't always navigate Unless in the case that the app has been cached in memory by Windows Waiting for the CoreWebView2Ready event to fire gets around this for me least.Chanel
T
1

If you can access your control in code behind, you can use the CoreWebView2InitializationCompleted event handler to have a state, where CoreWebView2 is initialized. (WebView2 is the x:name of the control in my case.)

        WebView2.CoreWebView2InitializationCompleted += (sender, args) =>
        {
            if (args.IsSuccess)
            {
                var vw2 = (WebView2)sender;
                vw2!.CoreWebView2.Settings.AreDevToolsEnabled = false;
            }
        };

See the tooltip of the event handler in the latest versions for more information.

Using WebView2 1.0.1108.44.

Tolland answered 1/3, 2022 at 15:38 Comment(0)
C
0

Documentation reports it is a heavy operation and so I recommend initialization of corewebview2 when it is needed. An example in VB.net is below:

Dim uriFile as string = "https://YourURLgoeshere"
    Try
      If WebView21 IsNot Nothing AndAlso Webview21.CoreWebView2 IsNot Nothing Then
         WebView21.CoreWebView2.Navigate(uriFile)
      Else
         WebView21.Source = New Uri(uriFile)
      End If
    Catch x As Exception
      'Do some exception management...
      
    End Try
Cerium answered 3/7, 2021 at 17:44 Comment(0)
G
0

If it is windows application, make sure you have InitializeComponent() method in your form constructor.

Gang answered 24/10, 2021 at 13:4 Comment(0)
P
0

I had trouble along similar lines for my Windows Forms desktop application (.NET Framework). I used the following code in my Page_Load event (code in VB.NET, but should be easy to convert to C#)

WebView21.CreationProperties = New Microsoft.Web.WebView2.WinForms.CoreWebView2CreationProperties

Dim currentDirectory As String = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

Dim strDir As String = currentDirectory & "\WebView2Runtime\Microsoft.WebView2.FixedVersionRuntime.99.0.1150.46.x86"  

WebView21.CreationProperties.BrowserExecutableFolder = strDir 

WebView21.Source = New Uri("Your URL")

I saved the WebView2Runtime folder (downloaded from the Fixed Version section of Microsoft's webpage on WebView2) in the Debug folder of my Visual Studio project.

An important point that I learnt from Microsoft's WebView2 webpage is that the path where the WebView2Runtime is saved should be called absolutely (for example C:\... and not as a UNC path ("Double Backslash...") and should not be a network location (I guessed from this that the project executable file and the WebView2Runtime should be on the same drive. So, I saved everything to C:.

Partiality answered 24/3, 2022 at 18:46 Comment(0)
B
0

If you reached here and your issue still has not been solved, please also note that the version of "WebView2Loader.dll" which is in use is very crucial. I had almost the same problem with "Microsoft.WebView2.FixedVersionRuntime.101.0.1210.39.x64" when I tried to use the WebView2 component in the MMC Snap-Ins with types of "HTMLView" or "FormView".

I just copied the abovementioned dll file (version 1.0.1248.0, size=157640 bytes) in a proper path that was accessible for the project (you could just put it beside your project output files first to test it) and then WebView2 browser started to function as expected. Microsoft error messages sometimes (at least in my case) was a little bit misleading and did not convey enough and to the point information.

I received "BadImageFormatException" that normally occurs when you mix platform targets (for example using a dll file compiled in X64 in an application that targeted for x86 or vice versa) or mix native code and .NET but that was not my problem at all. I hope this help one who may stuck in.

Bounder answered 18/5, 2022 at 8:3 Comment(0)
K
0

EnsureCoreWebView2Async didnt help in my case. The only thing that worked was to uninstall and reinstall webview2 runtime from apps & features.

Kuo answered 19/9, 2022 at 10:58 Comment(0)
D
0

I had the same problem... I was developing for Windows 10 using Visual Studio 2013 with the latest version of the Webview2 nuget package, everything worked perfectly. The problem started when I had to migrate to Windows 7, I noticed that coreWebView2 is null. I solved the problem by doing two things. I copied the runtime folder that contains the WebView2Loader.dll to the same folder as my executable and set the Specific Version = True property of the Microsoft.Web.WebView2.Core and Microsoft.Web.WebView2.WinForms references. I also downloaded the webview2 nuget package version 1.0.1587.40. With this I was able to run my program normally on Windows 7

Dewar answered 18/7, 2023 at 2:47 Comment(1)
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From ReviewMcnalley

© 2022 - 2024 — McMap. All rights reserved.