Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

718
Visualizações
two way communication between c# and JS using webview2

I'm using a webview2-control in a winforms application. I use messages to communicate between c# and Javascript

  • window.chrome.webview.addEventListener / window.chrome.webview.postMessage in Javascript
  • event .CoreWebView2.WebMessageReceived and method CoreWebView2.PostWebMessageAsString in C#

The communication works BUT only after the page in webview2 has been somehow refreshed. The first message sent by c# is always ignored/not received by JS. The messages after that are correcly received and processed.

My UI code:

public GUI()
{
    InitializeComponent();
    browser.Source = new Uri(System.IO.Path.GetFullPath("HTML/ui.html"));
    InitializeAsync();
}
async void InitializeAsync()
{
    await browser.EnsureCoreWebView2Async(null);
    browser.CoreWebView2.WebMessageReceived += MessageReceived;
    }
void MessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
    String content = args.TryGetWebMessageAsString();
    if (content.StartsWith("getData"))
    {
        ReadDataFromCATIA();
        var serializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects };
        string jsonRootNode = JsonConvert.SerializeObject(this.RootNode, Formatting.Indented, serializerSettings); //here I've got the message I want to post
        //String input = args.TryGetWebMessageAsString();
        //MessageBox.Show("string from JS: " + input);
        browser.CoreWebView2.PostWebMessageAsString(jsonRootNode);
    }
    else //object received
    {
        ProductNode received = JsonConvert.DeserializeObject<ProductNode>(content);
        MessageBox.Show(received.PartNumber + " received");
    }
}

and my JS in ui.html

window.chrome.webview.addEventListener('message', event => {
    alert(event.data);
    WriteDataFromCsharp(event.data);
});
function WriteDataFromCsharp(data) {
    var target = document.getElementById('target');
    if (target === null) { alert('target not found') };
    //alert(target.id);
    //target.textContent = event.data;

    rootNode = JSON.parse(data);
    target.innerHTML = addTable(rootNode); //addTable create an HTML table from the deserialized object rootNode
}
function RequestData() {
    //function triggered by a button on the html page
    //alert('post to c#');
    window.chrome.webview.postMessage('getData');
}

So far, i've tried to:

  • ensure the javascript is as late as possible in the page (defer, at the end of body). No changes.
  • inject the javascript to the page after it has been loaded using .CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(jsCode). Same behavior.
  • inject the javascript after once the event NavigationCompleted has fired. same behavior.

What do I miss ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Finally found the culprit: in my HTML-page, i've used a "submit" instead of "button". With

<input type="button" value="Load data from V5" onclick="RequestData()" />

The page behavior is as expected.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda