Memories of CEFGlue

Preface

When I had just graduated and started working, I spent some time studying CEF and solved several fairly painful problems. After changing direction later, I stopped paying attention to it. Then, a few days ago, someone I did not know somehow found my QQ and added me to ask a few CEF-related questions. At that moment I suddenly realized that this experience might be worth recording. This is written for myself from four years ago.

Background

On the .NET platform, Microsoft’s built-in WebBrowser control has several problems:

  1. It cannot guarantee a consistent browser version. On Windows XP, you may be calling IE 6.0, while on Windows 7 or later, the version used by WebBrowser may still differ from the IE version installed on the machine.
  2. HTML compatibility is troublesome. Different browsers interpret the same page differently. Even when IE 8 or a newer IE browser is installed, the WebBrowser control defaults to IE7 compatibility mode, which causes many page styles to render incorrectly. For example, IE7 does not support HTML5. One workaround is to specify the IE version for your process in the registry.

More details can be found here.

To solve these problems more thoroughly, after some research we decided to use a third-party open-source browser: the Chromium Embedded Framework, or CEF. CEF is an open-source project created by Marshall Greenblatt in 2008. Its main purpose is to provide a WebBrowser control based on Google Chromium. CEF supports a range of programming languages and operating systems, and it can be integrated fairly easily into both new and existing projects.

Its design goal is ease of use while still taking performance into account. The basic CEF framework exposes C/C++ APIs through native libraries. These libraries isolate the host application from the implementation details of Chromium and WebKit. CEF provides tight integration between the browser control and the host application. It supports plugins, custom protocols, JavaScript objects, and JavaScript extensions. The host application can control resource downloading, navigation, printing, and more, while benefiting from performance and HTML5 support similar to Google Chrome.

Memories of CEFGlue: Background (figure 1)

The overall dependency structure of CEFGlue is shown above. There were two urgent and tricky problems:

    1. Make CEF support regular audio and video playback.
    1. Solve the problem of JavaScript calling native functionality.

CEF Audio and Video Support

To make CEF support common audio and video playback, the CEF kernel needs to be rebuilt.

CEF Kernel Build Process

The CEF kernel build process is full of tears. Anyone who has built it probably knows that feeling. Here is a summary of the steps and things to watch out for:

    1. The operating system must be Windows 7 Ultimate, and it must be 64-bit. 32-bit is not supported.
    1. The system language must be set to English, otherwise various encoding errors may appear. The setting is under Control Panel -> Region -> Administrative -> Language.
    1. Install Visual Studio 2013 Update 4. Earlier versions are not supported.
    1. Prepare a stable and reliable VPN. It must really be stable.
    1. Install depot_tools. After downloading it, unzip it directly. Download URL: https://src.chromium.org/svn/trunk/tools/depot_tools.zip
    1. Configure the depot_tools environment variables: set GYP_GENERATORS=ninja,msvs-ninja set GYP_MSVS_VERSION=2013 set DEPOT_TOOLS_WIN_TOOLCHAIN=0 set USE_PROPRIETARY_CODECS=1
    1. Download the Chromium source code. CEF cannot be built independently; it depends on Chromium. - Choose a folder without special characters or Chinese characters, such as workspace/chromium/. - Enter the folder and run fetch --nohooks chromium. This takes a very long time. If it fails midway, run gclient sync. - Determine the CEF kernel version, then determine the corresponding Chrome version, for example 4d096306deb9e86953c81f08454dd6db07b406b5. - Fetch the required Chromium revision: gclient sync --revision 4d096306deb9e86953c81f08454dd6db07b406b5 --jobs 16 This step can take a very long time, so patience is required.
    1. Copy the matching CEF source directory into chromium/src. Modify the CEF build options: open cef.gypi and add these two lines: 'proprietary_codecs': 1, 'ffmpeg_branding':'Chrome', To inspect detailed audio and video codec support, check: workspace\chromium\src\third_party\ffmpeg\chromium\scripts\build_ffmpeg.py
    1. Build CEF: export GYP_GENERATORS='ninja' cd workspace/chromium/src/cef cef_create_projects.bat cd workspace/chromium/src ninja -C out/Release cefclient cef_unittests
    1. Package the CEF kernel: cd workspace/chromium/src/cef/tools make_distrib.bat --ninja-build

CEF Kernel H5 Score

  • Chromium version: 43.0.2357.81
  • CEF version: 3.2357.1280.geba024d
  • Dependency chain: CEFGlue -> CEF -> Chromium
Memories of CEFGlue: CEF Kernel H5 Score (figure 2)

JavaScript Calling Native Functionality

Xilium CefGlue is an open-source WebKit-kernel browser project based on the Chromium Embedded Framework (CEF). It wraps many parts with .NET, has many advantages, and the kernel keeps evolving, so it has good prospects. However, it has one serious problem: CLR Object cannot interact smoothly with frontend JavaScript. The implementation is complicated and tedious.

Official Native Registration Method

The native method provided officially requires the class object to inherit from CefV8Handler. All operations must be written inside that class’s Execute() method. All properties and methods of the class object must have corresponding JavaScript code manually written in the background for registration and binding. If you want to perform different operations, you need to keep writing a large number of class objects, because each class can only do one thing.

The steps are as follows:

  1. Define MyV8Handler, inheriting from CefV8Handler. Note that the registered object must inherit from CefV8Handler, which means the registered object is constrained.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class MyV8Handler : CefV8Handler
{
public MyV8Handler()
{
this.name = "lingyun";
}

private string name;
public string Name
{
set { this.name = value; }
get { return this.name; }
}

public void MyFunction()
{
MessageBox.Show("JS调用C# : MyFunction");
}

private string email;
public string GetEmail()
{
return this.email;
}
public void SetEmail(string email)
{
this.email = email;
}
}
  1. Define WpfRenderProcessHandler, inheriting from CefRenderProcessHandler, and override the OnWebKitInitialized() event. Inside it, write the operations to execute, manually generate JavaScript according to the class structure, and register it through the official RegisterExtension method. Notice that registration is completed in OnWebKitInitialized, which means the timing is also constrained. Once WebKit initialization finishes, the registration opportunity is gone.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class WpfRenderProcessHandler:CefRenderProcessHandler
{
private MyV8Handler myHandle;
protected override void OnWebKitInitialized()
{
myHandle = new MyV8Handler();

const string jsCode = @"function myHandle() {}

if (!myHandle) myHandle = {};

(function() {

myHandle.__defineGetter__('name',
function() {
native function GetName();
return GetName();
});

myHandle.__defineSetter__('name',
function(arg0) {
native function SetName(arg0);
SetName(arg0);
});

myHandle.myFunction = function() {
native function MyFunction();
return MyFunction();
};

myHandle.getEmail = function() {
native function GetEmail();
return GetEmail();
};

myHandle.setEmail = function(arg0) {
native function SetEmail(arg0);
SetEmail(arg0);
};

})();";

CefRuntime.RegisterExtension("myHandleName", jsCode, myHandle);

base.OnWebKitInitialized();
}
}
  1. In the Execute() event of MyV8Handler, write the operation logic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
{
string result = string.Empty;
switch (name)
{
case "MyFunction":
MyFunction();
break;

case "GetEmail":
result = GetEmail();
break;

case "SetEmail":
SetEmail(arguments[0].GetStringValue());
break;

default:
break;
}

returnValue = CefV8Value.CreateString(result);
exception = null;
return true;
}
  1. Write a web page and call it from JavaScript, for example: myHandle.myFunction().

As you can see, registering one native method costs a lot. The native registration method is also rigid. To support different operations, you need to keep writing many class objects, because each class can only do one thing. This has neither generality nor extensibility, and the resulting code is almost lifeless.

Advanced Registration Method

Understanding the Core Registration Principle

Although the official registration approach is extremely verbose, the core principle is not hard to discover: registration essentially asks the V8 context to remember a method name and its parameter count and types. It tells the V8 engine that when it encounters a registered name, it should pass the method name and arguments out through the Execute method, and then native code can match and invoke the local method. As for who calls Execute and how it is called, the V8 engine handles that; we do not need to care.

Once this core principle is clear, and since .NET has good reflection support, it is natural to infer that given a CLR object, we can use reflection to analyze its method list and obtain the parameter count and parameter type list for each method. With that information, we can register automatically and implement a general-purpose registration scheme.

Multi-process Communication Solution

Starting from CEF 3.0, CEF moved from the old single-process model to a multi-process model. For example, rendering is handled by a dedicated render process, while the main process, the Browser process, communicates with the Render process through message passing.

Because registered objects can only be registered in the V8 context, and the V8 context can only be accessed by the Render process, registering a native object usually means serializing the native object in the Browser process, sending it to the Render process, deserializing it there, and then registering it.

Memories of CEFGlue: Multi-process Communication Solution (figure 3)

However, this approach runs into a serious practical problem: not every object in .NET supports serialization. This is especially true when the object comes from an already packaged DLL that we cannot modify. Therefore this route does not work. I also considered shared memory, but in the end it still could not avoid serialization.

After digging deeper into CEF’s internal registration mechanism, I found that registration only cares about the object’s method names and property names; it does not care about the concrete implementation of those methods. So the Browser process can first store the real object in its own object pool, then use reflection to parse the object’s method names and property names and send only that metadata to the Render process. After receiving the method and property names, the Render process performs the actual registration in its own context.

Once JavaScript calls a native method and triggers CefV8Handler.Execute, the Render process obtains the object hash, method name, and arguments, and sends them back to the Browser process. The Browser process then finds the real object in the local registration pool and chooses the best matching method to invoke. In other words, actual execution happens entirely in the Browser process, while the communication between Browser and Render only carries method names and simple argument data, avoiding object serialization.

Memories of CEFGlue: Multi-process Communication Solution (figure 4)

Here are several English excerpts about CEF multi-process communication that inspired me:

I have been struggling with this as well. I do not think there is a way to do this synchronously…or easily :) Perhaps what can be done is this:

From browser do sendProcessMessage with all JS information to renderer process. You can pass all kinds of parameters to this call in a structured way so encapsulating the JS method name and params in order should not be difficult to do. In renderer process (RenderProcessHandler onProcessMessageReceived method) do TryEval on the V8Context and get the return value via out parameters and sendProcessMessage back to the browser process with the JS return value (Note that this supports ordinary return semantics from your JS method).You get the browser instance reference in the onProcessMessageReceived so it is as easy as this (mixed pseudo code) browser.GetMainFrame().CefV8Context.tryEval(js-code,out retValue, out exception); process retValue; browser.sendProcessMessage(…); Browser will get a callback in the WebClient in onProcessMessageReceived. There is nothing special here in terms of setting up JS. I have for example a loaded html page with a js function in it. It takes a param as input and returns a string. in js-code parameter to TryEval I simply provide this value:

It is slightly convoluted but seems like a neat workable approach – better than doing ExecuteJavaScript and posting results via XHR on custom handler in my view. I tried this and it does work quite well indeed….and is not bad as it is all non-blocking. The wiring in the browser process needs to be done to process the response properly. This can be extended and built into a set of classes to abstract this out for all kinds of calls.. Take a look at the Xilium demo app. Most of the necessary wiring is already there for onProcessMessage – do a global search. Look for DemoRendererProcessHandler.cs – renderer side this is where you will invoke tryEval DemoApp.cs – this is browser side, look for sendProcessMessage – this will initiate your JS invocation process. WebClient.cs – this is browser side. Here you receive messages from renderer with return value from your JS Cheers.

Fully Automatic Reflection-based Registration

Combining the core registration principle with CEF’s multi-process communication model, and after reading some source code, the final solution can be broken down into these steps:

  1. Define MyV8Handler, but do not inherit from CefV8Handler anymore. This removes the inheritance restriction, which means any object in the program can be registered. The flexibility is greatly improved. The reason this works is the underlying CEF registration principle described above.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class MyV8Handler
{
public MyV8Handler()
{
this.name = "lingyun";
}

private string name;
public string Name
{
set { this.name = value; }
get { return this.name; }
}

public void MyFunction()
{
MessageBox.Show("JS调用C# : MyFunction");
}

private string email;
public string GetEmail()
{
return this.email;
}
public void SetEmail(string email)
{
this.email = email;
}
}
  1. Define CefGlueRuntime to start the CEF kernel and register native objects in the Browser process. This registration is only a fake registration: all it does is store the object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class CefGlueRuntime
{
private static object locker = new object();
public static bool Startup()
{
try
{
CefRuntime.Load();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}

string[] args = { };
var mainArgs = new CefMainArgs(args);
var cefApp = new WpfCefApp();
var exitCode = CefRuntime.ExecuteProcess(mainArgs, cefApp);
if (exitCode != -1) { return false; }

var cefSettings = new CefSettings
{
SingleProcess = true,
WindowlessRenderingEnabled = false,
MultiThreadedMessageLoop = true,
LogSeverity = CefLogSeverity.Disable,
NoSandbox = true,
UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/6.0; rv:8.0) like Gecko Chromiumembedded/43.0.2357.81 CefGlue/3.2357.1280.geba024d (cxb,Founder)"
};

try
{
CefRuntime.Initialize(mainArgs, cefSettings, cefApp);
}
catch (CefRuntimeException ex)
{
MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
return true;
}

public static void Shutdown()
{
lock (locker)
{
CefRuntime.Shutdown();
}
}

private static Dictionary<string, Dictionary<int, object>> ObjectsList = new Dictionary<string, Dictionary<int, object>>();

public static void RegisterJsObject(string exportName, Object obj,int hashCode)
{
if (!ObjectsList.ContainsKey(exportName))
{
var objDic = new Dictionary<int,object>();
objDic.Add(hashCode, obj);
ObjectsList.Add(exportName,objDic);
}
else{
if (!ObjectsList[exportName].ContainsKey(hashCode))
ObjectsList[exportName].Add(hashCode, obj);
}

if (!ObjectList.ContainsKey(hashCode))
ObjectList.Add(hashCode, obj);
}

public static Dictionary<string, Dictionary<int, object>> GetObjects()
{
return ObjectsList;
}

public static Dictionary<int, object> ObjectList = new Dictionary<int, object>();
}

In real situations, one exportName may correspond to multiple objects. Because serialization and deserialization change object hash values, the original hash should be passed in at the beginning, and that hash should be used to decide whether an object has already been registered. This solves duplicate registration.

  1. Define a WebView. In the Browser process, RegisterJsObject uses reflection to extract the object’s method list, the parameter count and parameter types of each method, and the property list. It packages this metadata and sends it to the Render process. At the same time, it calls CefGlueRuntime.RegisterJsObject to store the native object locally.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class WebView : WpfCefBrowser
{
public object result = string.Empty;
public string exceptionMessage = string.Empty;
public AutoResetEvent signal = new AutoResetEvent(false);

public void RegisterJsObject(string extentionName, object obj)
{
CefProcessMessage msg = CefProcessMessage.Create("Register");
CefListValue objInfo = msg.Arguments;

objInfo.SetString(0, extentionName);

int hashCode = obj.GetHashCode();
objInfo.SetInt(1, hashCode);

CefListValue methodList = CefListValue.Create();
HashSet<string> methodNames = TypeUtil.GetMethodNames(obj.GetType());
for (int i = 0; i < methodNames.Count; i++)
methodList.SetString(i, methodNames.ElementAt<string>(i));
objInfo.SetList(2, methodList);

CefListValue propertyList = CefListValue.Create();
var properties = TypeUtil.GetProperties(obj.GetType());
for (int i = 0; i < properties.Keys.Count; i++)
{
string propertyName = properties.Keys.ElementAt<string>(i);
CefV8PropertyAttribute propertyAttribute = CefV8PropertyAttribute.None;
if (properties[propertyName].GetSetMethod() != null)
propertyAttribute = CefV8PropertyAttribute.ReadOnly;
CefListValue propertyInfo = CefListValue.Create();
propertyInfo.SetString(0, propertyName);
propertyInfo.SetInt(1, (int)propertyAttribute);
propertyList.SetList(i, propertyInfo);
}
objInfo.SetList(3, propertyList);

this.SendProcessMessage(CefProcessId.Renderer, msg);

CefGlueRuntime.RegisterJsObject(extentionName, obj, hashCode);
}
}
  1. Define WpfRenderProcessHandler, inheriting from CefRenderProcessHandler. In OnProcessMessageReceived, receive messages from the Browser process. Registration messages are handled by ProcessRegisterMessage.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
protected override bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message)
{
if (message.Name == "Register")
{
ProcessRegisterMessage(message);
}
else if (message.Name == "EvaluteJavaScript")
{
if (CefRuntime.CurrentlyOn(CefThreadId.Renderer))
ProcessEvaluateMessage(browser, message);
else
Wrapper.Helpers.PostTask(CefThreadId.Renderer, Wrapper.Helpers.Apply(ProcessEvaluateMessage, browser, message));
}
else if (message.Name == "ExecuteMethodResult")
{
BindingHandler.exception = message.Arguments.GetString(0);
CefBinaryValue binaryValue = message.Arguments.GetBinary(1);
byte[] binaryData = binaryValue.ToArray();
BindingHandler.result = SerializationUtil.DeserializeObject(binaryData);
BindingHandler.signal.Set();
}
var handled = MessageRouter.OnProcessMessageReceived(browser, sourceProcess, message);
if (handled) return true;

return true;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void ProcessRegisterMessage(CefProcessMessage message)
{
var arguments = message.Arguments;

string extensionName = arguments.GetString(0);
int hashCode = arguments.GetInt(1);

CefListValue methodList = arguments.GetList(2);
List<string> ml = new List<string>();
for (int i = 0; i < methodList.Count; i++)
ml.Add(methodList.GetString(i));

CefListValue propertyList = arguments.GetList(3);
Dictionary<string, Dictionary<string, string>> pl = new Dictionary<string, Dictionary<string, string>>();
for (int i = 0; i < propertyList.Count; i++)
{
CefListValue propertyInfo = propertyList.GetList(i);
Dictionary<string, string> pi = new Dictionary<string, string>();
pi.Add("propertyName", propertyInfo.GetString(0));
pi.Add("propertyAttribute", propertyInfo.GetInt(1).ToString());
pl.Add(propertyInfo.GetString(0),pi);
}

CefRenderRuntime.RegisterJsObject(extensionName, hashCode, ml, pl);
}

Define CefRenderRuntime as the Render process object pool. It receives the metadata passed from the Browser process:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class CefRenderRuntime
{
private static Dictionary<string, Dictionary<int, List<string>>> methodList = new Dictionary<string, Dictionary<int, List<string>>>();
private static Dictionary<string, Dictionary<int, Dictionary<string, Dictionary<string, string>>>> propertyList = new Dictionary<string, Dictionary<int, Dictionary<string, Dictionary<string, string>>>>();
private static Dictionary<string, HashSet<int>> keys = new Dictionary<string, HashSet<int>>();

public static void RegisterJsObject(string exportName, int hashCode, List<string> ml, Dictionary<string,Dictionary<string, string>> pl)
{
if (!methodList.ContainsKey(exportName))
{
var methodDic = new Dictionary<int, List<string>>();
methodDic.Add(hashCode, ml);
methodList.Add(exportName, methodDic);
}
else
{
if (!methodList[exportName].ContainsKey(hashCode))
methodList[exportName].Add(hashCode, ml);
}

if (!propertyList.ContainsKey(exportName))
{
var propertyDic = new Dictionary<int, Dictionary<string,Dictionary<string, string>>>();
propertyDic.Add(hashCode, pl);
propertyList.Add(exportName, propertyDic);
}
else
{
if (!propertyList[exportName].ContainsKey(hashCode))
propertyList[exportName].Add(hashCode, pl);
}

if (!keys.ContainsKey(exportName))
{
var keyDic = new HashSet<int>();
keyDic.Add(hashCode);
keys.Add(exportName, keyDic);
}
else
{
keys[exportName].Add(hashCode);
}
}

public static List<string> GetMethods(string exportName, int hashcode)
{
return methodList[exportName][hashcode];
}

public static Dictionary<string,Dictionary<string, string>> GetProperties(string exportName, int hashcode)
{
return propertyList[exportName][hashcode];
}

public static Dictionary<string, HashSet<int>> GetKeys()
{
return keys;
}
}
  1. In WpfRenderProcessHandler.OnContextCreated, use BindingHandler to register. Note that this is no longer OnWebKitInitialized, but OnContextCreated. This means that even after WebKit starts, registration can still happen whenever each context is created. The registration timing is no longer locked down.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context)
{
var keys = CefRenderRuntime.GetKeys();
foreach (var key in keys.Keys)
{
var hashcodeList = keys[key];
foreach (int hashcode in hashcodeList)
{
BindingHandler.Bind(key, hashcode, context.GetGlobal(), browser);
}
}

MessageRouter.OnContextCreated(browser, frame, context);
base.OnContextCreated(browser, frame, context);
}

BindingHandler is defined as follows. It inherits from CefV8Handler. The Bind function is the core. The final key registration statement is window.SetValue, and what it registers is a CefV8Value object. Therefore, before registration, the CLR object must be converted into data that V8 can understand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class BindingHandler:CefV8Handler
{
public static void Bind(string name, int hashcode, CefV8Value window, CefBrowser browser)
{
var unmanagedWrapper = new UnmanagedWrapper(hashcode);

var propertyAccessor = new PropertyAccessor();
CefV8Value javascriptWrapper = CefV8Value.CreateObject(propertyAccessor);

javascriptWrapper.SetUserData(unmanagedWrapper);

var handler = new BindingHandler();
handler.OnSendExecuteMsgHandler -= browser.SendProcessMessage;
handler.OnSendExecuteMsgHandler += browser.SendProcessMessage;

unmanagedWrapper.Properties = CefRenderRuntime.GetProperties(name,hashcode);
CreateJavascriptProperties(handler, javascriptWrapper, unmanagedWrapper.Properties);

List<string> methodNames = CefRenderRuntime.GetMethods(name, hashcode);
CreateJavascriptMethods(handler, javascriptWrapper, methodNames);

window.SetValue(name, javascriptWrapper, CefV8PropertyAttribute.None);
}

public static void CreateJavascriptMethods(CefV8Handler handler, CefV8Value javascriptObject, List<String> methodNames)
{
var unmanagedWrapper = (UnmanagedWrapper)(javascriptObject.GetUserData());

foreach (string methodName in methodNames)
{
string jsMethodName = StringUtil.LowercaseFirst(methodName);
unmanagedWrapper.AddMethodMapping(jsMethodName, methodName);
string nameStr = jsMethodName;
javascriptObject.SetValue(nameStr, CefV8Value.CreateFunction(nameStr, handler), CefV8PropertyAttribute.None);
}
}

public static void CreateJavascriptProperties(CefV8Handler handler, CefV8Value javascriptObject, Dictionary<string,Dictionary<string, string>> properties)
{
var unmanagedWrapper = (UnmanagedWrapper)(javascriptObject.GetUserData());

foreach (var propertyInfo in properties.Values)
{
string propertyName = propertyInfo["propertyName"];
string jsPropertyName = StringUtil.LowercaseFirst(propertyName);
unmanagedWrapper.AddPropertyMapping(jsPropertyName, propertyName);
string nameStr = jsPropertyName;
CefV8PropertyAttribute propertyAttribute = (CefV8PropertyAttribute)(int.Parse(propertyInfo["propertyAttribute"]));
javascriptObject.SetValue(nameStr, CefV8AccessControl.Default, propertyAttribute);
}
}
}
  1. Write a web page and call from JavaScript, such as myHandle.myFunction(). This first triggers BindingHandler.Execute in the Render process. That method parses the method name and arguments passed from JavaScript. TypeUtil converts V8 data types into CLR data types. Then the parsed data is packaged and sent to the Browser process.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class BindingHandler:CefV8Handler
{
protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
{
returnValue = CefV8Value.CreateNull();
result = string.Empty ;
exception = string.Empty;

UnmanagedWrapper unmanagedWrapper = obj.GetUserData() as UnmanagedWrapper;
int hashcode = unmanagedWrapper.GetHashCode();
if (hashcode == 0)
{
exception = "Binding's CLR object is null.";
return true;
}

string methodName = unmanagedWrapper.GetMethodMapping(name);

var suppliedArguments = new object[arguments.Length];
try
{
for (int i = 0; i < suppliedArguments.Length; i++)
suppliedArguments[i] = TypeUtil.ConvertFromCefV8Value(arguments[i]);
}
catch (Exception err)
{
exception = err.Message;
return true;
}

CefProcessMessage msg = CefProcessMessage.Create("ExecuteMehtod");
CefListValue args = msg.Arguments;
args.SetInt(0, hashcode);
args.SetString(1, methodName);
SetArguments(suppliedArguments,ref args);

if (this.OnSendExecuteMsgHandler != null)
this.OnSendExecuteMsgHandler(CefProcessId.Browser, msg);

BindingHandler.signal.WaitOne();

if (!string.IsNullOrEmpty(BindingHandler.exception))
{
exception = BindingHandler.exception;
return true;
}
returnValue = TypeUtil.ConvertToCefV8Value(BindingHandler.result, BindingHandler.result.GetType());

return true;
}
}
  1. In the Browser process, OnProcessMessageReceived receives the message from the Render process that asks it to execute the method. It parses the method name and arguments, calls BindingHandler.ExecuteMethod, and finally sends the return value back to the Render process.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class WebView : WpfCefBrowser
{
public override bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message)
{
if (message.Name == "EvaluteJavaScriptResult")
{
this.exceptionMessage = message.Arguments.GetString(0);
CefBinaryValue binaryValue = message.Arguments.GetBinary(1);
byte[] binaryData = binaryValue.ToArray();
this.result = SerializationUtil.DeserializeObject(binaryData);

signal.Set();
return true;
}
else if (message.Name == "ExecuteMehtod")
{
CefListValue args = message.Arguments;
int hashcode = args.GetInt(0);
string methodName = args.GetString(1);
object[] arguments = new object[args.Count-2];
for (int i = 2; i < args.Count; i++)
{
var type = args.GetValueType(i);
if (type == CefValueType.Bool)
arguments[i-2] = args.GetBool(i);
else if (type == CefValueType.Int)
arguments[i-2] = args.GetInt(i);
else if (type == CefValueType.Double)
arguments[i-2] = args.GetDouble(i);
else if (type == CefValueType.String)
arguments[i-2] = args.GetString(i);
}
var obj = CefGlueRuntime.ObjectList[hashcode];

BindingHandler.ExecuteMethod(obj, methodName, arguments);

CefProcessMessage msg = CefProcessMessage.Create("ExecuteMethodResult");
CefListValue retargs = msg.Arguments;
retargs.SetString(0, BindingHandler.exception);
byte[] serializeObj = SerializationUtil.SerializeObject(BindingHandler.result);
retargs.SetBinary(1, CefBinaryValue.Create(serializeObj));
this.SendProcessMessage(CefProcessId.Renderer, msg);
return true;
}
return false;
}
}

BindingHandler.ExecuteMethod is shown below. It first calls FindBestMethod to match the most suitable method, and then invokes it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public static void ExecuteMethod(object obj, string methodName, object[] suppliedArguments)
{
var type = obj.GetType();
var methods = type.GetMember(methodName, MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public);
if (methods.Length == 0)
{
BindingHandler.exception = "No method named " + methodName + ".";
}

MethodInfo bestMethod = null;
object[] bestMethodArguments = null;
FindBestMethod(methods, suppliedArguments, ref bestMethod, ref bestMethodArguments);

if (bestMethod != null)
{
try
{
object result = bestMethod.Invoke(obj, bestMethodArguments);
if(result != null)
BindingHandler.result = TypeUtil.ConvertToCefV8Value(result, bestMethod.ReturnType);
}
catch (TargetInvocationException err)
{
BindingHandler.exception = err.Message;
}
catch (Exception e)
{
BindingHandler.exception = e.Message;
}
}
else
{
BindingHandler.exception = "Argument mismatch for method \"" + methodName + "\".";
}
}

The method matching logic in FindBestMethod is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public static void FindBestMethod(MemberInfo[] methods, object[] suppliedArguments, ref MethodInfo bestMethod,ref object[] bestMethodArguments)
{
var bestMethodCost = -1;
for (int i = 0; i < methods.Length; i++)
{
MethodInfo method = methods[i] as MethodInfo;
var parametersInfo = method.GetParameters();

if (parametersInfo.Length == 0)
{
if (suppliedArguments.Length == 0)
{
bestMethod = method;
bestMethodArguments = suppliedArguments;
bestMethodCost = 0;
break;
}
}
else
{
int failed = 0;
int cost = 0;
var arguments = new List<object>();
try
{
int p, a;

for (p = 0, a = 0; failed==0 && p < parametersInfo.Length && a < suppliedArguments.Length; p++)
{
ParameterInfo pi = parametersInfo[p];
Type paramType = pi.ParameterType;
if (paramType.IsArray && paramType.GetElementType() == typeof(object))
{
if (p < parametersInfo.Length - 1){
failed++;
break;
}

var parm = new List<object>();
for (; a < suppliedArguments.Length; a++)
parm.Add(suppliedArguments[a]);
arguments.Add(parm.ToArray());
cost += arguments.Count * 2;
}
else
{
int paramCost = TypeUtil.GetChangeTypeCost(suppliedArguments[a], paramType);
if (paramCost < 0){
failed++;
break;
}
arguments.Add(TypeUtil.ChangeType(suppliedArguments[a++], paramType));
cost += paramCost;
}
}
}catch(Exception e){
failed++;
}

if (failed > 0)
continue;
if (cost < bestMethodCost || bestMethodCost < 0)
{
bestMethod = method;
bestMethodArguments = arguments.ToArray();
bestMethodCost = cost;
}
if (cost == 0)
break;
}
}
}

It iterates through all methods and matches arguments one by one. If there are no parameters and no supplied arguments, it returns directly. Otherwise, it calculates conversion costs, rejects methods whose parameters cannot be converted, and picks the method with the lowest cost. This allows overloaded methods to be selected more reasonably.

Summary

This article mentioned two problems.

The first is building the CEF kernel. It requires patience and persistence.

The second is supporting JavaScript calls into native functionality. The key is to follow these two paths:

  1. Registration path: CLR object -> Browser process stores it -> reflection parses method names and parameters -> metadata is sent to the Render process -> BindingHandler registers it in the V8 engine.
  2. Invocation path: H5 calls a method -> Execute in the Render process parses the method name and arguments -> a message is sent to the Browser process -> the Browser process calls BindingHandler.ExecuteMethod -> the return value is sent back to the Render process.
-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:Memories of CEFGlue

Author:lingyun

Published:2018-05-26 01:08

Updated:2026-10-08 00:23

Original link:https://tsuijunxi.github.io/en/2018/05/26/cefglue-memories/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.