-
Notifications
You must be signed in to change notification settings - Fork 6
Javascript
Riekelt Brands edited this page Apr 2, 2021
·
9 revisions
You can evaluate Javascript both with and without callback.
To evaluate without a callback simply call CefInstance.Eval(string javascript)
Example
CefInstance.Eval("window.location.href = 'https://www.google.com/';");
To evaluate with a callback, you can call CefInstance.EvalCallback(string javascript, Action<string> callback)
Example
CefIntance.EvalCallback("window.location.href = 'https://www.google.com/';", (string result) => {
Debug.Log(result); // https://www.google.com
});
By default a Javascript object can be exposed to invoke static methods in your static classes.
To get the static method invoker, you need to call CefSharp.BindObjectAsync("staticInvoker");
in Javascript.
Now you can call staticInvoker.invoke(class, method, arguments[], callback);
.
Note: you will always receive a string
result as an argument in your callback, and you can only use strings as arguments. Use JSON for effective communication.
Example
using UnityEngine;
public static class InvokeTest
{
public static string Test(string arguments)
{
Debug.Log(arguments);
return "Hello from Unity!";
}
}
<html>
<body>
<h1>Hello world!</h1>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
(async function()
{
await CefSharp.BindObjectAsync("staticInvoker");
var updateH1 = function(result) {
$('h1').text(result);
}
staticInvoker.invoke('InvokeTest', 'Test', ['Hello from Javascript'], updateH1);
})();
</script>
</body>
</html>