ios 如何在目标 C 中调用 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14334047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call JavaScript Function in objective C
提问by Himesh
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 的新程序员。我向目标 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>
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()"];
回答by Serhii Mamontov
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:
回答by umakanta
<!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
为避免警告 :::从编译源中删除它们
回答by Evgenii
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:
这是一个演示:
回答by Jayprakash Dubey
FileName.js :
文件名.js :
function greet() {
hello(“This is Javascript function!”);
}
Copy this file into Bundle resources.
将此文件复制到捆绑资源中。
Now #import <JavaScriptCore/JavaScriptCore.h>
in header file
现在#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:@[]];
This code block worked for me. It displays "This is Javascript function!" in console. Hope this works!
这个代码块对我有用。它显示“这是 Javascript 函数!” 在控制台中。希望这有效!
回答by Nag Raj
Try this:
尝试这个:
NSString *jsCallBack = [NSString stringWithFormat:@"setPhoto('%@')",profileImgPath];
[webView stringByEvaluatingJavaScriptFromString:jsCallBack];