MicrosoftEdge / MicrosoftEdge/WebView2Feedback

CoreWebView2 is null

Open
#3,490 5 comments 0 reactions 1 assignee View on GitHub

Nobody has claimed this yet.

bug
Dominant language
PowerShell
Stars
526
Forks
67
PR merge metrics
No merged PRs in 30d

Description

I got CoreWebView2 null

I use this two methods in c#

public void InvokeBrowserScript(string functionName, string parameter, Action action = null)
{
try
{
Log.Write($"Invoking script: {functionName}, parameter: {parameter}");
_webView.Dispatcher.InvokeAsync(async () =>
{
var message = new { messageType = functionName, messageData = parameter };
var json = JsonConvert.SerializeObject(message);
PostMessageToWeb(json);
action?.Invoke(json);

            });
        }
        catch (Exception ex)
        {
            Log.Write($"Invoking script error: {ex}");
        }
    }

    /// <summary>
    /// From the container code(C#) you can call PostWebMessageAsJson() to pass
    /// JSON object to Angular layer. We are passing the functionname(messageType) and data(messageData)
    /// In the angular layer we can access the functionname and data through window.chrome.webview.addEventListener  
    /// </summary>
    /// <param name="json"></param>
    private void PostMessageToWeb(string json)
    {
        _webView.CoreWebView2?.PostWebMessageAsJson(json);
    }

I used
///


/// Call the container code from web side (angular code)
/// In the angular code we can access container methods like - window.chrome.webview.hostObjects.external.MethodName()
///

private void AddHostObject()
{
_webView.CoreWebView2.AddHostObjectToScript("external", new WebViewModel());

    }

so when i call a c# method from angular window.chrome.webview?.hostObjects.external.GetDeviceStatus()

Below is the c# method

public void GetDeviceStatus()
{
Task.Run(() =>
{
Log.Write("GetDeviceStatusinvoked");
InvokeBrowserScript("getInDeviceStatusComplete", ThreadManager.GetInBayStatus());
});
}
By AddHostObject() it calls GetDeviceStatus() from angular 15 layer to container,
But when InvokeBrowserScript("getInDeviceStatusComplete", ThreadManager.GetDeviceStatus());
called then in CoreWebView2 is null (InvokeBrowserScript calls PostMessageToWeb(json); in which CoreWebview2 is null )
How to fix this?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.