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

时间:2022-03-15 16:58:10

I am new programmer to objective C. I added some html file to Objective C. In this html file contains simple javascript function. I need to call that Function through thw objective C code. I tried lot of time by using google. But I could not find real way to do it. Bellow Contains html File :

我是目标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>

I called this function like this : Is it correct or wrong ?? If it wrong, how to do this. Please help.

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

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

5 个解决方案

#1


26  

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

If all this code called from single place, than it won't work, because page load is asynchronous and page with JavaScript code is not ready at that moment. Try to call this methods [webView stringByEvaluatingJavaScriptFromString:@"myFunction()"]; in UIWebViewDelegate callback method –webViewDidFinishLoad:

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

#2


9  

<!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>

Add a html file to project folder. Add your javascript file also to project folder.

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

After adding the html file and this native code to your viewController.m

将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");
}

Call this in your didLoad method [self loadMyWebView];

在你的didLoad方法[self loadMyWebView]中调用它;

Here you can add any javascript file to the project and include it to the html file. You can call javascript function inside the tag. (exactly as you used to call js functions. )

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

You can pass any parameter to javascript function and return anything to objective function.

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

Remember ::: After adding all js file don't forget to add them to Copy Bundle Resources

记住:::添加所有js文件后别忘了将它们添加到Copy Bundle Resources

To avoid warning ::: remove them from Compile Sources

为了避免警告:::从Compile Sources中删除它们

#3


8  

One can use JavaScriptCore framework to run JavaScript code from Objective-C.

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

Here is a demo:

这是一个演示:

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

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

#4


1  

FileName.js :

FileName.js:

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

Copy this file into Bundle resources.

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

Now #import <JavaScriptCore/JavaScriptCore.h> in header file

现在#import 在头文件中

 @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:@[]];

This code block worked for me. It displays "This is Javascript function!" in console. Hope this works!

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

#5


0  

Try this:

尝试这个:

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

[webView stringByEvaluatingJavaScriptFromString:jsCallBack];

#1


26  

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

If all this code called from single place, than it won't work, because page load is asynchronous and page with JavaScript code is not ready at that moment. Try to call this methods [webView stringByEvaluatingJavaScriptFromString:@"myFunction()"]; in UIWebViewDelegate callback method –webViewDidFinishLoad:

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

#2


9  

<!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>

Add a html file to project folder. Add your javascript file also to project folder.

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

After adding the html file and this native code to your viewController.m

将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");
}

Call this in your didLoad method [self loadMyWebView];

在你的didLoad方法[self loadMyWebView]中调用它;

Here you can add any javascript file to the project and include it to the html file. You can call javascript function inside the tag. (exactly as you used to call js functions. )

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

You can pass any parameter to javascript function and return anything to objective function.

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

Remember ::: After adding all js file don't forget to add them to Copy Bundle Resources

记住:::添加所有js文件后别忘了将它们添加到Copy Bundle Resources

To avoid warning ::: remove them from Compile Sources

为了避免警告:::从Compile Sources中删除它们

#3


8  

One can use JavaScriptCore framework to run JavaScript code from Objective-C.

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

Here is a demo:

这是一个演示:

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

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

#4


1  

FileName.js :

FileName.js:

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

Copy this file into Bundle resources.

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

Now #import <JavaScriptCore/JavaScriptCore.h> in header file

现在#import 在头文件中

 @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:@[]];

This code block worked for me. It displays "This is Javascript function!" in console. Hope this works!

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

#5


0  

Try this:

尝试这个:

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

[webView stringByEvaluatingJavaScriptFromString:jsCallBack];