Home > OS >  Why won't CefSharp.PostMessage work in CefSharp browser?
Why won't CefSharp.PostMessage work in CefSharp browser?

Time:03-06

I tried using JavascriptMessageReceived event in c# to handle CefSharp.PostMessage called from JS within the browser. I even downloaded an example of this working from link. Ran example which was supposed to do exactly what I needed, but it didn't work, nor does my code (below). Did CefSharp remove this functionality or change it? Do I need to enable this feature within the CefSettings or ChromiumWebBrowser?

using CefSharp;
using CefSharp.WinForms;

public ChromiumWebBrowser chromeBrowser;

public Form1()
    {
        InitializeComponent();

        string curDir = Directory.GetCurrentDirectory();
        CefSettings settings = new CefSettings();
        Cef.Initialize(settings);
        chromeBrowser = new ChromiumWebBrowser(String.Format("file:///{0}/HelloWorld.html", curDir));
        chromeBrowser.JavascriptMessageReceived  = ChromeBrowser_JavascriptMessageReceived;
    }

private void ChromeBrowser_JavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
    {
        MessageBox.Show((string)e.Message);
    }

HelloWorld.html here

<!DOCTYPE html>
<html>
<body>

<script>
CefSharp.PostMessage("Hello world!");
</script>

</body>
</html>

CodePudding user response:

  1. CefSharp.PostMessage("Hello world!"); is a quite new JS extension of 2020. Make sure your are using the actual CefSharp.
  2. chromeBrowser = new ChromiumWebBrowser(String.Format("file:///{0}/HelloWorld.html", curDir));
    chromeBrowser.JavascriptMessageReceived  = ChromeBrowser_JavascriptMessageReceived;
    
    The subscription on JavascriptMessageReceived events is too late, the page might be downloaded and JS might be executed to that moment. You should subscribe on events before page load.
    chromeBrowser = new ChromiumWebBrowser("about:blank");
    chromeBrowser.JavascriptMessageReceived  = ChromeBrowser_JavascriptMessageReceived;
    chromeBrowser.Load(String.Format("file:///{0}/HelloWorld.html", curDir));
    
  3. Make sure HelloWorld.html is existing in the application current working directory.

CodePudding user response:

Where are you adding the ChromiumWebBrowser to the form? The WinForms ChromiumWebBrowser control won't load until it's handle is created which by default happens when it's added to a parent.

chromeBrowser = new ChromiumWebBrowser(String.Format("file:///{0}/HelloWorld.html", curDir));
chromeBrowser.JavascriptMessageReceived  = ChromeBrowser_JavascriptMessageReceived;
Controls.Add(chromeBrowser);
  • Related