iOS: Native调用js的方法以及js回调native的方法

iOS: JS和Native交互的两种方法

背景:

UIWebView: iOS 用来展示 web 端内容的控件。

1. 核心方法:

- (NSString*)stringByEvaluatingJavaScriptFromString:(NSString *)script;
script 就是 JS 代码,返回结果为 js 执行结果。 比如一个 JS function 为
function testFunction(abc){
  return abc;
};
function testFunction(abc){
  return abc;
};

webview 调用此 JS 代码如下:

NSString *js = @"testFunction('abc')";
NSString *result = [webView stringByEvaluatingJavaScriptFromString:js];

 

2. 重要回调:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

webview 每当需要去加载一个 request 就先回调这个方法,让上层决定是否 加载。一般在这里截获,进行本地的处理。

 

Native 调用 JS:

本质就一个方法,通过 stringByEvaluatingJavaScriptFromString,都是同步。

 

下面重点说说JS怎么回调Native:

1.通常方法:js通过doucument的loaction或者新建一个看不见的iFrame,修改它的 src,就会触发回调 webView 的 shouldStartLoadWithRequest,参数 request 的 url 就是新赋值的 location 或者 url,上层截获这个 url 的参数,对此分发即可。 这个都是异步调用的。

如 JS function:

    var messagingIframe;
    messagingIframe = document.createElement('iframe');
    messagingIframe.style.display = 'none';
    document.documentElement.appendChild(messagingIframe);

    function TestIOSJS(){
        messagingIframe.src = "ios/test/click";
    };

当触发上面的JS时,webview会收到下面的回调:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    if([url hasSuffix:@"ios/test/click"]){
        //do something you want
        return NO;
    }
    return YES;
}

 

通过截获这个request的参数就可以做native需要做的事情。

有个开源的代码挺不错的,大家可以看看:https://github.com/marcuswestin/WebViewJavascriptBridge

2.通过XMLHttpRequest:

  (1) Native子类化一个NSURLProtocol类,并通过[NSURLProtocol registerClass:self];把自己注册。

  (2) JS function 创建一个 XMLHttpRequest 对象,然后可以设置携带的参数,设置同步或者异步,然后通过 send 发送请求。

 

 

    function iOSExec(){
        var execXhr = new XMLHttpRequest();
        execXhr.open('HEAD', "/!test_exec?" + (+new Date()), true); //设置scheme
        var vcHeaderValue = /.*\((.*)\)/.exec(navigator.userAgent)[1];
        execXhr.setRequestHeader('vc', vcHeaderValue);//设置参数等
        execXhr.setRequestHeader('rc', 1);
        // 发起请求
        execXhr.send(null);
    };

 

 

  (3) 因为步骤1已经把自己注册,所以每个客户端的网络请求都会请求这个类 的+(BOOL)canInitWithRequest:(NSURLRequest *)request,让此决定是否需要生成这个request。

  

@implementation TestURLProtocol

+(void)initProtocol
{
    [NSURLProtocol registerClass:self];
}

+(BOOL)canInitWithRequest:(NSURLRequest *)request{
    NSString *url = request.URL.absoluteString;
    if([url containsString:@"!test_exec"]){
        //do something
    }
    return NO;
}

  (4) 通过获取这个request的参数,上层可以进行拦截,然后进行本地的相 关操作。 

这个方法比较少用,不过能解决JS同步回调Native的方法。

这里也有一个开源库,大家可以看一下:https://github.com/apache/cordova-ios/tree/master/CordovaLib

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在JavaScript中调用iOS方法需要使用JavaScript与原生iOS之间的交互技术。以下是一些方法: 1. 使用UIWebView执行JavaScript代码 可以使用UIWebView在iOS应用程序中执行JavaScript代码。UIWebView对象提供了一个方法,可以通过该方法将JavaScript代码传递给UIWebView并执行它。在JavaScript代码中,可以使用window.location来调用iOS方法。例如: ``` window.location = "ios://methodName?param1=value1&param2=value2"; ``` 在iOS应用程序中,可以在UIWebView的委托方法中截取这个请求,解析参数,并调用相应的方法。例如: ``` - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL *url = request.URL; if ([[url scheme] isEqualToString:@"ios"]) { NSString *methodName = [url host]; NSDictionary *params = [self parseParams:[url query]]; // call the iOS method with the given name and parameters [self callMethod:methodName withParams:params]; return NO; } return YES; } ``` 2. 使用JavaScriptCore框架 JavaScriptCore框架是一个内置于iOS中的JavaScript引擎。可以使用它来执行JavaScript代码并与原生iOS进行交互。可以使用JSContext对象来将JavaScript代码传递给JavaScript引擎并执行它。在JavaScript代码中,可以使用JSContext对象的evaluateScript方法调用iOS方法。例如: ``` var methodName = "methodName"; var param1 = "value1"; var param2 = "value2"; var result = MyObjCClass.callNativeMethod(methodName, param1, param2); ``` 在iOS应用程序中,可以创建一个MyObjCClass类来处理JavaScript传递的调用请求,并返回结果。例如: ``` JSContext *context = [[JSContext alloc] init]; context[@"MyObjCClass"] = [MyObjCClass class]; [context evaluateScript:@"var methodName = 'methodName'; var param1 = 'value1'; var param2 = 'value2'; var result = MyObjCClass.callNativeMethod(methodName, param1, param2);"]; ``` 以上是两种在JavaScript中调用iOS方法方法。当然,具体的实现方案需要根据具体的需求和场景进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值