如何在目标C中调用JavaScript函数

时间:2013-01-15 08:51:00

标签: ios uiwebview

我是目标C的新程序员。我在Objective C中添加了一些html文件。在这个html文件中包含简单的javascript函数。我需要通过目标C代码调用该函数。我通过谷歌尝试了很多时间。但我找不到真正的方法来做到这一点。  Bellow包含html文件:

<!DOCTYPE html>
<html>
    <head>
        <script>
            function myFunction()
            {
                alert("Hello World!");
            }
            </script>
    </head>

    <body>
        <button onclick="myFunction()">Try it</button>
    </body>
</html>

我这样称呼这个函数:它是正确还是错误?如果错了,该怎么做。请帮忙。

NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:@"first" ofType:@"html"];
NSURL *instructionsURL = [NSURL fileURLWithPath:path];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];

 NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
 [webView stringByEvaluatingJavaScriptFromString:jsCallBack];

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

6 个答案:

答案 0 :(得分:28)

NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:@"first" ofType:@"html"];
NSURL *instructionsURL = [NSURL fileURLWithPath:path];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];

 NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
 [webView stringByEvaluatingJavaScriptFromString:jsCallBack];

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

如果从单个地方调用所有这些代码,那么它将无法工作,因为页面加载是异步的,并且当时没有准备好带有JavaScript代码的页面。 尝试在UIWebViewDelegate回调方法[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];

中调用此方法–webViewDidFinishLoad:

答案 1 :(得分:10)

<!DOCTYPE html>
<html>
<head>

    <script type="text/javascript" charset="utf-8" src="your.js"></script>
    <script type="text/javascript" charset="utf-8" src="andYourJsfileName.js"></script>

    <script>
        function myFunction('yourParameter') 
        {
            // do your javascript operation

            //alert("my Hello World!");
            return value;
        }

    </script>
</head>

<body>
    <!--button onclick="myFunction()">Try it</button-->
</body>

将html文件添加到项目文件夹。 将您的javascript文件也添加到项目文件夹。

将html文件和此本机代码添加到viewController.m

之后
-(void)loadMyWebView {
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)];
    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"first" ofType:@"html"];
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];

    NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    webView.delegate=self;

    [webView loadHTMLString:htmlString baseURL:instructionsURL];
    // [self.view addSubview:webView];  (if you want to access the javascript function and don't want to add webview, you can skip that also.)
}


- (void)webViewDidFinishLoad:(UIWebView*)theWebView {
    NSString* returnValue =[theWebView stringByEvaluatingJavaScriptFromString:@"myFunction('pass your parameter')"];
    NSLog(@"returnValue = %@ ",returnValue);
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

    NSLog(@" didFailLoadWithError");
}

在didLoad方法[self loadMyWebView];

中调用此方法

在这里,您可以将任何javascript文件添加到项目中,并将其包含在html文件中。你可以在标签内调用javascript函数。 (就像你以前调用js函数一样。)

您可以将任何参数传递给javascript函数并将任何内容返回给目标函数。

记住::: 添加所有js文件后,不要忘记将它们添加到 复制捆绑资源

要避免警告::: 编译来源

中删除它们

答案 2 :(得分:8)

可以使用JavaScriptCore框架从Objective-C运行JavaScript代码。

#import <JavaScriptCore/JavaScriptCore.h>

...

JSContext *context = [[JSContext alloc] init];
[context evaluateScript: @"function greet(name){ return 'Hello, ' + name; }"];
JSValue *function = context[@"greet"];
JSValue* result = [function callWithArguments:@[@"World"]];
[result toString]; // -> Hello, World

这是一个演示:

https://github.com/evgenyneu/ios-javascriptcore-demo

答案 3 :(得分:2)

FileName.js:

function greet() {
    hello(“This is Javascript function!”);
}

将此文件复制到Bundle资源中。

现在#import <JavaScriptCore/JavaScriptCore.h>在头文件

 @property (nonatomic,strong) JSContext *context; // Declare this in header file

       // This code block goes into main file
        NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"js"];
        NSString *scriptString = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];

        self.context = [[JSContext alloc] init];
        [self.context evaluateScript:scriptString];

        self.context[@"hello"] = ^(NSString text) {
            NSLog(@"JS : %@",text);
        }

        JSValue *function = self.context[@"greet"];
        [function callWithArguments:@[]];

这个代码块对我有用。它显示“这是Javascript函数!”在控制台。 希望这有效!

答案 4 :(得分:0)

试试这个:

NSString *jsCallBack = [NSString stringWithFormat:@"setPhoto('%@')",profileImgPath];

[webView stringByEvaluatingJavaScriptFromString:jsCallBack];

答案 5 :(得分:0)

demo.js文件:

function say(data) {
  return data;
}

ViewController.m

- (NSString *)invokeJS {

    NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"];
    NSLog(@"path: %@", scriptPath);
    NSString *script = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];
    
    self.context = [[JSContext alloc] init];
    [self.context evaluateScript:script];
    
    JSValue *function = self.context[@"say"];//invoke function name
    JSValue *data = [function callWithArguments:@[@"Hello World"]];//invoke function argument
 
    NSString *result = [data toString];//the result: Hello World

    return result;
}