Why my coreWebView2 which is object of webView2 is null?

40.1k views Asked by At

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
17

There are 17 answers

0
J-Rome On

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

9
Ryan Wilson On

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)

1
Огњен Шобајић On

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;
0
Nikhil On

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:.

0
SWIK On

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

0
amirfg On

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.

0
Xpleria On

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!

0
Andrew On

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
1
William On

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

1
efebilici On

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)
0
Ranjana 006 On
    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/");
    }
0
Adam On

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();
    }
}
1
Chris Cullen On

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();
    }
}
0
nkanani On

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.

0
AntiTalent On

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.

0
Rajender Gottipamula On

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

0
ppchavan001 On

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