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:
CefSharp.PostMessage("Hello world!");
is a quite new JS extension of 2020. Make sure your are using the actual CefSharp.-
The subscription onchromeBrowser = new ChromiumWebBrowser(String.Format("file:///{0}/HelloWorld.html", curDir)); chromeBrowser.JavascriptMessageReceived = ChromeBrowser_JavascriptMessageReceived;
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));
- 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);