注入JS代码:
cefApp.SetOnWebKitInitialized(func() { var myparamValue string v8Handler := cef.V8HandlerRef.New() v8Handler.Execute(func(name string, object *cef.ICefV8Value, arguments *cef.TCefV8ValueArray, retVal *cef.ResultV8Value, exception *cef.ResultString) bool { fmt.Println("v8Handler.Execute", name) var result bool if name == "GetMyParam" { result = true retVal.SetResult(cef.V8ValueRef.NewString(myparamValue)) } else if name == "SetMyParam" { if arguments.Size() > 0 { newValue := arguments.Get(0) fmt.Println("value is string:", newValue.IsString()) fmt.Println("value:", newValue.GetStringValue()) myparamValue = newValue.GetStringValue() newValue.Free() } result = true } return result }) //注册js var jsCode = ` let test; if (!test) { test = {}; } (function () { test.__defineGetter__('myparam', function () { native function GetMyParam(); return GetMyParam(); }); test.__defineSetter__('myparam', function (b) { native function SetMyParam(); if (b) SetMyParam(b); }); })(); ` // 注册JS 和v8处理器 cef.RegisterExtension("v8/test", jsCode, v8Handler) })
JS里可以这样使用:
<script type="application/javascript"> function SetMyParam() { test.myparam = document.getElementById("newvalue").value; } function GetMyParam() { msg("GetMyParam", test.myparam); } </script> <input id="newvalue" value="new value"/> <button onclick="SetMyParam()">Set myparam value</button> <button onclick="GetMyParam()">Get myparam value</button> <p id="msgHtml"></p>