24

我是 Objective C 的新程序员。我在 Objective C 中添加了一些 html 文件。在这个 html 文件中包含简单的 javascript 函数。我需要通过目标 C 代码调用该函数。我用谷歌尝试了很多时间。但我找不到真正的方法来做到这一点。波纹管包含 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()"];
4

6 回答 6

33
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 代码的页面此时还没有准备好。尝试[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];在 UIWebViewDelegate 回调方法中调用此方法–webViewDidFinishLoad:

于 2013-01-15T09:22:13.550 回答
12
<!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 文件后不要忘记将它们添加到Copy Bundle Resources

为了避免警告 :::从编译源 中删除它们

于 2013-08-21T11:31:51.377 回答
9

可以使用 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

于 2013-11-03T11:36:50.410 回答
2

文件名.js:

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

将此文件复制到捆绑资源中。

现在#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 函数!” 在控制台中。希望这有效!

于 2014-03-25T13:29:30.710 回答
1

试试这个:

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

[webView stringByEvaluatingJavaScriptFromString:jsCallBack];
于 2014-03-12T06:27:35.920 回答
0

demo.js 文件:

function say(data) {
  return data;
}

视图控制器.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;
}

于 2020-12-08T07:06:51.437 回答