Xamarin IOS 无法在 JavascriptCore 中绑定函数或回调
Xamarin IOS Cant Bind function or callback In JavascriptCore
按照此处的示例:JSContext
我收到以下异常:
{TypeError: myCSharpObject.myFunc is not a function. (In 'myCSharpObject.myFunc()', 'myCSharpObject.myFunc' is undefined)}
我的代码如下:
JSContext _context;
_context = new JSContext();
var jsCallback = new MyJSExporter();
_context[(NSString)"myCSharpObject"] = JSValue.From(jsCallback, _context);
var result = _context.EvaluateScript("myCSharpObject.myFunc();");
协议定义为:
[Protocol]
interface IMyJSVisibleProtocol : IJSExport
{
[Export("myFunc")]
int MyFunc();
[Export("Arity2:With:")]
NSObject Arity2With(NSObject arg1, NSObject arg2);
}
class MyJSExporter : NSObject, IMyJSVisibleProtocol
{
public int MyFunc()
{
Console.WriteLine("Called!");
return 42;
}
public NSObject Arity2With(NSObject arg1, NSObject arg2)
{
Console.WriteLine("Arity 2 function called with " + arg1 + " " + arg2);
return (NSNumber)42;
}
}
异常处理程序为:
_context.ExceptionHandler = (context, exception) => {
// {TypeError: myCSharpObject.myFunc is not a function. (In 'myCSharpObject.myFunc()', 'myCSharpObject.myFunc' is undefined)}
};
您使用了错误的 JSContext。
在您的代码中,您正在初始化新的 JSContext。相反,您想从文档中获取您在 webView 中加载的内容:var context = (JSContext)webView.ValueForKeyPath((NSString)"documentView.webView.mainFrame.javaScriptContext");
最终为我解决这个问题的是添加构建 mtouch 参数:
'--注册商:static'
按照此处的示例:JSContext
我收到以下异常:
{TypeError: myCSharpObject.myFunc is not a function. (In 'myCSharpObject.myFunc()', 'myCSharpObject.myFunc' is undefined)}
我的代码如下:
JSContext _context;
_context = new JSContext();
var jsCallback = new MyJSExporter();
_context[(NSString)"myCSharpObject"] = JSValue.From(jsCallback, _context);
var result = _context.EvaluateScript("myCSharpObject.myFunc();");
协议定义为:
[Protocol]
interface IMyJSVisibleProtocol : IJSExport
{
[Export("myFunc")]
int MyFunc();
[Export("Arity2:With:")]
NSObject Arity2With(NSObject arg1, NSObject arg2);
}
class MyJSExporter : NSObject, IMyJSVisibleProtocol
{
public int MyFunc()
{
Console.WriteLine("Called!");
return 42;
}
public NSObject Arity2With(NSObject arg1, NSObject arg2)
{
Console.WriteLine("Arity 2 function called with " + arg1 + " " + arg2);
return (NSNumber)42;
}
}
异常处理程序为:
_context.ExceptionHandler = (context, exception) => {
// {TypeError: myCSharpObject.myFunc is not a function. (In 'myCSharpObject.myFunc()', 'myCSharpObject.myFunc' is undefined)}
};
您使用了错误的 JSContext。
在您的代码中,您正在初始化新的 JSContext。相反,您想从文档中获取您在 webView 中加载的内容:var context = (JSContext)webView.ValueForKeyPath((NSString)"documentView.webView.mainFrame.javaScriptContext");
最终为我解决这个问题的是添加构建 mtouch 参数:
'--注册商:static'