javascript 从javascript调用objective-c方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21927612/
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
Call objective-c method from javascript
提问by Mehman Bashirov
I make any webView And I want to call from javascript any objective c method which return any parameter. I tried many ways but not allowed . Objective c method here:
我制作任何 webView 并且我想从 javascript 调用任何返回任何参数的目标 c 方法。我尝试了很多方法但不允许。这里的目标c方法:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:@"donordialog"])
{
// now we need to figure out the function part
NSString *functionString = [URL resourceSpecifier];
if ([functionString hasPrefix:@"bloodTypeChanged"])
{
// the blood type has changed, now do something about it.
NSString *parameter = [functionString stringByReplacingOccurrencesOfString:@"bloodTypeChanged" withString:@""];
// remove the '(' and then the ')'
parameter = [parameter stringByReplacingOccurrencesOfString:@"(" withString:@""];
parameter = [parameter stringByReplacingOccurrencesOfString:@")" withString:@""];
// log the paramter, as I don't know what to do with it right now
UIAlertView *alert=[[ UIAlertView alloc] initWithTitle:@"iosdan javascripti"
message:@"ddddddddd"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
//NSLog(@"%@", parameter);
}
return NO;
}
return YES;
}
javascript:
javascript:
function myFunction() {
url="http://example.com";
window.location="donordialog:blooTypeChanged("+url+")";
}
html:
html:
<button onclick="myFunction()">click me</button>
comment: I need that: it is obj c method for example. aaa{} . My aaa method must return any parameter. and I have wevView. I loaded any url to this webView: for example www.example.com/forios . I need call this (aaa) method from javascript which it is in html on www.example.com/forios and alert the result of aaa function. understand?. If understand, dont watch to my code. help please yourself anyway. android version of my question:Call Java function from JavaScript over Android WebViewI want to alert some parameter returning from method. Help please. Thanks.
评论:我需要:例如,它是 obj c 方法。啊{}。我的 aaa 方法必须返回任何参数。我有wevView。我将任何 url 加载到此 webView:例如 www.example.com/forios 。我需要从 javascript 调用这个 (aaa) 方法,它位于 www.example.com/forios 上的 html 中,并提醒 aaa 函数的结果。理解?。如果理解,请不要看我的代码。无论如何请帮助自己。我的问题的 android 版本:Call Java function from JavaScript over Android WebView我想提醒一些从方法返回的参数。请帮忙。谢谢。
采纳答案by Mykola Denysyuk
The most usual approach that I used to interact from javascript within obj-c is to changing hash. On required event in your js write
window.location.hash = '#cmd_alertMessage';
after this your - (BOOL)webView: shouldStartLoadWithRequest: navigationType:
will be called:
我用来在 obj-c 中与 javascript 交互的最常用方法是更改哈希。在您的 js 中的必需事件写入
window.location.hash = '#cmd_alertMessage';
之后,您- (BOOL)webView: shouldStartLoadWithRequest: navigationType:
将被调用:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSArray * compenents = [request.URL.absoluteString componentsSeparatedByString:@"#"];
if (compenents.count > 1) {
NSString * cmd = compenents[1];
if ([cmd rangeOfString:@"cmd_alertMessage"].location != NSNotFound) {
// Call your obj-c method and get appropriated param
NSString * jsFunction = [NSString stringWithFormat:@"setParameterFromAAAMethod('%@')", [self aaa]];
// Return this param back to js
NSString * alertMessage = [webView stringByEvaluatingJavaScriptFromString:jsFunction];
}
}
return YES;
}
- (NSString *)aaa
{
return @"This is special parameter that you need";
}
So, it will work in 3 steps:
因此,它将分 3 个步骤工作:
- Invoke hash changing to request parameter from obj-c code in js;
- Handle hash changed (parameter request) and return in back to js in obj-c;
- Handle recieved parameter in js again
- 调用哈希更改以从js 中的obj-c 代码请求参数;
- 处理哈希改变(参数请求)并返回到obj-c 中的js ;
- 再次处理js 中收到的参数
回答by Fusion Radio Dev
Here is a quick and easy solution withoutJavaScriptCore for backwards compatibility (might consider upgrading to Javascriptcore ). Here's an easy implementation.
这是一个快速简便的解决方案,没有JavaScriptCore 以实现向后兼容性(可能会考虑升级到 Javascriptcore )。这是一个简单的实现。
Note: this solution is for UIwebview only (not UIscrollview)
注意:此解决方案仅适用于 UIwebview(不适用于 UIscrollview)
//viewcontroller.h
//视图控制器.h
@interface ViewController : UIViewController<UIWebViewDelegate>
@property (strong, nonatomic) IBOutlet UIWebView *viewWeb;
@end
//viewcontroller.m
//视图控制器.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *fullURL = @"http:player.fusion.fm";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
_viewWeb.delegate = self;
}
-(BOOL)webView:(UIWebView *)_viewWeb shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = request.URL;
if ([[url scheme] isEqualToString:@"ios"])
{
[self mute]; // <-- YOUR OBJ-C FUNCTION HERE
NSLog(@"test");
return YES;
}else
{
return YES;
}
}
// The Javascript (within webview)
// Javascript(在 webview 中)
try
{
window.location="ios://null"
}
catch(err)
{
}
资料来源:http: //adoptioncurve.net/archives/2012/09/calling-objective-c-methods-from-javascript-in-a-uiwebview/
回答by Janis Kirsteins
You can set a hidden iframe's location to something specific to your app, and then intercept that request in Obj-C.
您可以将隐藏的 iframe 的位置设置为特定于您的应用程序的位置,然后在 Obj-C 中拦截该请求。
Here's an overview and some examples: http://blog.techno-barje.fr//post/2010/10/06/UIWebView-secrets-part3-How-to-properly-call-ObjectiveC-from-Javascript/
这是概述和一些示例:http: //blog.techno-barje.fr//post/2010/10/06/UIWebView-secrets-part3-How-to-properly-call-ObjectiveC-from-Javascript/
回答by Piyush Dubey
Well, I am not sure whether I got your question correct or not, but if you want to call any javascript method, then you can do this way:-[yourWebView stringByEvaluatingJavaScriptFromString:@"yourMethodName()"];
You can also pass parameters in above method.
好吧,我不确定我的问题是否正确,但是如果您想调用任何 javascript 方法,那么您可以这样做:-[yourWebView stringByEvaluatingJavaScriptFromString:@"yourMethodName()"];
您也可以在上述方法中传递参数。