我希望能够在我的应用程序中使用 PhoneGap。我将不得不构建一个自定义协议(protocol)/插件,以便我可以从 Javascript 调用 native 方法。我知道您可以在 native 代码返回时在 Javascript 中调用成功函数。
我需要做的是从 native 代码调用 javascript 函数。基本上,该应用程序将通过本地网络连接到 OSX 配套应用程序,当 OSX 应用程序将数据发送到 iOS 应用程序时,它在 Objective C 方法中进行处理,我需要能够将结果发送到 PhoneGap/javascript 并做一些事情在 WebView 中使用它。
这可能吗?我只能找到有关从 javascript 调用 native 的信息,而不是相反。
谢谢, 托马斯
使用下面答案中的代码:
MyPhoneGapPlugin.m
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@"Connected To %@:%i.", host, port);
NSString* jsString = [NSString stringWithFormat:@"alert(connected to: %@);", host];
[theWebView stringByEvaluatingJavaScriptFromString:jsString];
[self readWithTag:2];
}
给我错误“未知接收者‘theWebView’,你是说‘UIWebView’吗?”
更新:找到答案:使用 phonegap 助手我可以写这样的东西......
[super writeJavascript:@"alert('connected');"];
最佳答案
您可以使用 UIWebView
从 native 代码轻松调用 JavaScript:
[webView stringByEvaluatingJavaScriptFromString:@"myJSFunction()"];
将某处函数的结果用作 JS 函数的参数:
NSString *stringData = getStringData(); // however you get it
[webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"myJSFunction(%@)", stringData]];
关于javascript - 您可以使用 PhoneGap 和 iOS 从 native 代码(不在回调中)调用 javascript 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7719881/