[英]Callback on a website not working using CefSharp in C#
Im trying to get a callback using cefsharp on a website i dont own.我试图在我不拥有的网站上使用 cefsharp 进行回调。
On the launching of my application i bind the tag "cb"在启动我的应用程序时,我绑定了标签“cb”
chromeBrowser.JavascriptObjectRepository.Register("cb", new BoundObject(), true);
public class BoundObject
{
public void dosomthing()
{
MessageBox.Show("It worked!");
}
}
Using the following javascript script i add an object to the website:使用以下 javascript 脚本,我将 object 添加到网站:
function insertBefore(el, referenceNode) {
referenceNode.parentNode.insertBefore(el, referenceNode);
}
var newEl = document.createElement('div');
newEl.className = 'exampleclass';
newEl.innerHTML = '<a onclick="cb.dosomthing();">Do somthing</a>';
var ref = document.getElementById('example-tab');
insertBefore(newEl, ref);
I perform this using:我使用以下方法执行此操作:
ExecuteScriptAsyncWhenPageLoaded
Then when i click the added in element with the text "Do somthing", nothing happens.然后,当我单击带有文本“Do somthing”的添加元素时,没有任何反应。
What am i doing wrong?我究竟做错了什么?
JavaScript binding requires that you call CefSharp.BindObjectAsync
in javascript before you can access the object. JavaScript 绑定要求您在访问 object 之前调用
CefSharp.BindObjectAsync
中的 CefSharp.BindObjectAsync。 I also recommend wrapping your code in an anon closure when it's more than a single line.我还建议在代码不止一行时将代码包装在匿名闭包中。
An example would look something like一个例子看起来像
(async function()
{
await CefSharp.BindObjectAsync("cb");
//Object with name cb will have been bound, you can now access
function insertBefore(el, referenceNode) {
referenceNode.parentNode.insertBefore(el, referenceNode);
}
var newEl = document.createElement('div');
newEl.className = 'exampleclass';
newEl.innerHTML = '<a onclick="cb.dosomthing();">Do somthing</a>';
var ref = document.getElementById('example-tab');
insertBefore(newEl, ref);
})();
Also MessageBox.Show
should be called on the UI
thread, the BoundObject.dosomething
method will be called on a background thread. MessageBox.Show
也应该在UI
线程上调用, BoundObject.dosomething
方法将在后台线程上调用。 A simple solution is to pass a reference to your Form/Window/Control
(not sure if you are using WinForms
or WPF
, so I cannot say exactly) then Invoke the call back onto your UI
thread.一个简单的解决方案是传递对您的
Form/Window/Control
的引用(不确定您是使用WinForms
还是WPF
,所以我不能确切地说)然后将调用调用回您的UI
线程。 For testing purposes what you have should be ok, if you want to do anything more serious then you should change your code.出于测试目的,你应该没问题,如果你想做更严重的事情,那么你应该改变你的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.