7

我希望能够将 PhoneGap 用于我的应用程序。我将不得不构建一个自定义协议/插件,以便我可以从 Javascript 调用本机方法。我知道当本机代码返回时,您可以在 Javascript 中调用成功函数。

我需要做的是从本机代码中调用一个 javascript 函数。基本上,该应用程序将通过本地网络连接到 OSX 配套应用程序,当 OSX 应用程序将数据发送到 iOS 应用程序时,它会以 Objective C 方法进行处理,我需要能够将结果发送到 PhoneGap/javascript 并做一些事情在 WebView 中使用它。

这可能吗?我只能找到有关从 javascript 调用本机的信息,而不是相反。

谢谢,托马斯

在这里使用来自答案的代码:

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');"];
4

4 回答 4

10

您可以使用以下命令轻松地从本机代码调用 JavaScript UIWebView

[webView stringByEvaluatingJavaScriptFromString:@"myJSFunction()"];

要将某个函数的结果用作 JS 函数的 arg:

NSString *stringData = getStringData(); // however you get it
[webView stringByEvaluatingJavaScriptFromString:
 [NSString stringWithFormat:@"myJSFunction(%@)", stringData]];
于 2011-10-10T23:44:01.740 回答
4

找到了 PhoneGap 帮助器来完成此操作...使用以下方法将 javascript 写入 webView:

    [super writeJavascript:@"alert('it works');"];
于 2011-10-24T23:09:28.853 回答
2

你应该试试这个

[webView stringByEvaluatingJavaScriptFromString:@"sendSelectedDate()"];
于 2012-09-13T19:11:32.760 回答
0

这对你有用吗?

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DisplayWebContent/Tasks/JavaScriptFromObjC.html

取自此页面:

您还可以使用参数调用 JavaScript 函数。假设您编写了一个如下所示的 JavaScript 函数:

function addImage(image, width, height) { ... }

其目的是将图像添加到网页。它用三个参数调用:image,图像的 URL;width,图像的屏幕宽度;和 height,图像的屏幕高度。您可以从 Objective-C 中以两种方式之一调用此方法。第一个在使用 WebScriptObject 桥之前创建参数数组:

id win = [webView windowScriptObject];



NSArray *args = [NSArray arrayWithObjects:
                 @"sample_graphic.jpg",
                 [NSNumber numberWithInt:320],
                 [NSNumber numberWithInt:240],
                  nil];

[win callWebScriptMethod:@"addImage"
            withArguments:args];
于 2011-10-10T23:43:39.503 回答