为什么 CefSharp.PostMessage 在 CefSharp 浏览器中不起作用?
我尝试在 C# 中使用 JavascriptMessageReceived 事件来处理浏览器中从 JS 调用的 CefSharp.PostMessage 。我什至从 链接。运行示例本来应该完全满足我的需要,但它不起作用,我的代码也不起作用(如下)。 CefSharp 是否删除或更改了此功能?我是否需要在 CefSettings 或 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 在这里
<!DOCTYPE html>
<html>
<body>
<script>
CefSharp.PostMessage("Hello world!");
</script>
</body>
</html>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CefSharp.PostMessage("Hello world!");
是 2020 年的一个相当新的 JS 扩展。确保您使用的是实际的 CefSharp。对 JavascriptMessageReceived 事件的订阅太晚了,页面可能会被下载,并且 JS 可能会在此时执行。您应该在页面加载之前订阅事件。
CefSharp.PostMessage("Hello world!");
is a quite new JS extension of 2020. Make sure your are using the actual CefSharp.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.您在哪里将 ChromiumWebBrowser 添加到表单中? WinForms ChromiumWebBrowser 控件在创建其句柄之前不会加载,默认情况下,在将其添加到父级时会发生这种情况。
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.