【问题标题】:How to call JavaScript Function in objective C如何在目标 C 中调用 JavaScript 函数
【发布时间】:2013-01-15 08:50:59
【问题描述】:

我是 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()"];

【问题讨论】:

  • 警报是否显示?
  • 当我点击按钮时,它会显示出来。但我想以编程方式调用该函数。
  • 你想达到什么目的?您的应用程序是 HTML5 类型的吗?为什么不使用原生 UIKit?
  • 先试试[webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];,确定不是myFunction()的问题
  • 我的目的是通过objective c将参数传递给html(javascript)。我想像报告一样显示 html 页面。所以我想用参数调用javascript函数。所以我尝试了这样的简单代码。我没有使用原生 UIKit。 @pbibergal 谢谢

标签: ios uiwebview


【解决方案1】:
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回调方法–webViewDidFinishLoad:中调用这个方法[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];

【讨论】:

  • 非常感谢您的回答。它是 100% 工作的。再次感谢。
  • 答案非常正确。我正在为此提供额外的功能谢谢!
  • 请告诉我们如何使用 iOS 8 wkwebview?
  • @moonlight 我正在尝试使此代码正常工作,只是为了在我的 ios 应用程序中添加一些功能(我习惯于 android)但路径为零(当然我更改了“第一”到我的文件名:主页)你知道这是为什么吗?如果我想在 ApplicationDelegate 中使用此代码,我应该将 webView 更改为 self.viewController.webView 吗?
  • 我们可以在不打开 webView 的情况下在 URL 上执行 jsContext 吗?
【解决方案2】:
<!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

为避免警告 :::编译源

中删除它们

【讨论】:

【解决方案3】:

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

【讨论】:

【解决方案4】:

文件名.js:

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

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

现在 #import &lt;JavaScriptCore/JavaScriptCore.h&gt; 在头文件中

 @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 函数!”在控制台中。 希望这行得通!

【讨论】:

    【解决方案5】:

    试试这个:

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

    【讨论】:

      【解决方案6】:

      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;
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-28
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-30
        相关资源
        最近更新 更多