第一种方式
JS传值给OC
- 1、技术方案:使用自定义url方法,每次点击网页
- 2、使用场景:比如点击事件方法,点击网页的某个方法,将该方法的参数传值给OC,供OC使用。
- 3、代码实现如下:
一、js要实现的
- 1 、 创建一个.js文件:
;(function() {
var messagingIframe,
bridge = 'external',
// wmcall是自定义的协议头
CUSTOM_PROTOCOL_SCHEME = 'wmcall';
if (window[bridge]) { return }
function _createQueueReadyIframe(doc) {
messagingIframe = doc.createElement('iframe');
messagingIframe.style.display = 'none';
doc.documentElement.appendChild(messagingIframe);
}
window[bridge] = {};
var methods = [%@];
for (var i=0;i<methods.length;i++){
var method = methods[i];
var code = "(window[bridge])[method] = function " + method + "() {messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + ':' + arguments.callee.name + ':' + encodeURIComponent(JSON.stringify(arguments));}";
eval(code);
}
//创建iframe,必须在创建external之后,否则会出现死循环
_createQueueReadyIframe(document);
//通知js开始初始化
//initReady();
})();
二、oc要实现的代码
- 2、 创建文件WebViewJsBridge.h, 继承UIWebViewDelegate
#import <Foundation/Foundation.h>
#define kCustomProtocolScheme @"wmcall"
#define kBridgeName @"external"
@interface WebViewJsBridge : NSObject<UIWebViewDelegate>
@property (nonatomic, weak) UIWebView *webView;
+ (instancetype)bridgeForWebView:(UIWebView*)webView webViewDelegate:(NSObject<UIWebViewDelegate>*)webViewDelegate;
+ (instancetype)bridgeForWebView:(UIWebView*)webView webViewDelegate:(NSObject<UIWebViewDelegate>*)webViewDelegate resourceBundle:(NSBundle*)bundle;
- (void)excuteJSWithObj:(NSString *)obj function:(NSString *)function;
@end
- WebViewJsBridge.m
#import "WebViewJsBridge.h"
#import <objc/runtime.h>
@interface WebViewJsBridge ()
@property (nonatomic, weak) id webViewDelegate;
@property (nonatomic, weak) NSBundle *resourceBundle;
@end
@implementation WebViewJsBridge
+ (instancetype)bridgeForWebView:(UIWebView*)webView webViewDelegate:(NSObject<UIWebViewDelegate>*)webViewDelegate {
return [self bridgeForWebView:webView webViewDelegate:webViewDelegate resourceBundle:nil];
}
+ (instancetype)bridgeForWebView:(UIWebView*)webView webViewDelegate:(NSObject<UIWebViewDelegate>*)webViewDelegate resourceBundle:(NSBundle*)bundle
{
WebViewJsBridge* bridge = [[[self class] alloc] init];
[bridge _platformSpecificSetup:webView webViewDelegate:webViewDelegate resourceBundle:bundle];
return bridge;
}
#pragma mark - init & dealloc
- (void) _platformSpecificSetup:(UIWebView*)webView webViewDelegate:(id<UIWebViewDelegate>)webViewDelegate resourceBundle:(NSBundle*)bundle{
_webView = webView;
_webViewDelegate = webViewDelegate;
_webView.delegate = self;
_resourceBundle = bundle;
}
- (void)dealloc {
_webView.delegate = nil;
_webView = nil;
_webViewDelegate = nil;
}
#pragma mark - UIWebView Delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (webView != _webView) { return; }
//is js insert
if (![[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"typeof window.%@ == 'object'", kBridgeName]] isEqualToString:@"true"]) {
//get class method dynamically
unsigned int methodCount = 0;
Method *methods = class_copyMethodList([self class], &methodCount);
NSMutableString *methodList = [NSMutableString string];
for (int i=0; i<methodCount; i++) {
NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(methods[i])) encoding:NSUTF8StringEncoding];
//防止隐藏的系统方法名包含“.”导致js报错
if ([methodName rangeOfString:@"."].location!=NSNotFound) {
continue;
}
[methodList appendString:@"\""];
[methodList appendString:[methodName stringByReplacingOccurrencesOfString:@":" withString:@""]];
[methodList appendString:@"\","];
}
if (methodList.length>0) {
[methodList deleteCharactersInRange:NSMakeRange(methodList.length-1, 1)];
}
free(methods);
NSBundle *bundle = _resourceBundle ? _resourceBundle : [NSBundle mainBundle];
NSString *filePath = [bundle pathForResource:@"WebViewJsBridge" ofType:@"js"];
NSString *js = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:js, methodList]];
}
__strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate;
if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
[strongDelegate webViewDidFinishLoad:webView];
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if (webView != _webView) { return; }
__strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate;
if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
[strongDelegate webView:webView didFailLoadWithError:error];
}
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (webView != _webView) { return YES; }
NSURL *url = [request URL];
__strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate;
// 拿到网页的实时url
NSString *requestString = [[request URL] absoluteString];
//在url中寻找自定义协议头"wmcall"
if ([requestString hasPrefix:kCustomProtocolScheme]) {
// 以":"为中心将url分割成两部分,放进数组arr。。是否取“:”或者“://”需要跟写交互的确定下
NSArray *components = [[url absoluteString] componentsSeparatedByString:@":"];
// 取其后半段
NSString *function = (NSString*)[components objectAtIndex:1];
NSString *argsAsString = [(NSString*)[components objectAtIndex:2]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *argsData = [argsAsString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *argsDic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:argsData options:kNilOptions error:NULL];
//以":"为标识将后半段url分割成若干部分,放进数组arr2,此时arr2[0]为空,arr2[1]为第一个传参值,arr2[2]为第二个传参值,以此类推
//convert js array to objc array
NSMutableArray *args = [NSMutableArray array];
//取出参数,进行使用
for (int i=0; i<[argsDic count]; i++) {
[args addObject:[argsDic objectForKey:[NSString stringWithFormat:@"%d", i]]];
}
//ignore warning
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
SEL selector = NSSelectorFromString([args count]>0?[function stringByAppendingString:@":"]:function);
if ([self respondsToSelector:selector]) {
[self performSelector:selector withObject:args];
}
return NO;
} else if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
return [strongDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
} else {
return YES;
}
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
if (webView != _webView) { return; }
__strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate;
if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
[strongDelegate webViewDidStartLoad:webView];
}
}
#pragma mark - call js
//执行js方法
- (void)excuteJSWithObj:(NSString *)obj function:(NSString *)function {
NSString *js = function;
if (obj) {
js = [NSString stringWithFormat:@"%@.%@", obj, function];
}
[self.webView stringByEvaluatingJavaScriptFromString:js];
}
@end
三、使用案例
- 1、创建桥接文件WebViewJsBridge.h
- .h
#import "WebViewJsBridge.h"
typedef void(^bridge_callback)(NSString* method, NSArray* params);
@interface BeeWebViewBridge : WebViewJsBridge
@property (nonatomic, strong) bridge_callback block_bridge_callback;
- (void)setBlock_bridge_callback:(bridge_callback)block_bridge_callback;
- (void)check_exist;
@end
- .m
#import "BeeWebViewBridge.h"
@implementation BeeWebViewBridge
//图片展示
- (void)show_image:(NSArray *)params
{
if(_block_bridge_callback)
{
_block_bridge_callback(@"show_image", params);
}
}
@end
oc传值给js
- 在webviewcontroller里面实现如下代码:
//通过paramsName,匹配需要传什么值
- (void)callByValueWithParamsName:(NSString *)paramsName
{
//要传出去的值
NSString *value = @"";
if ([paramsName isEqualToString:@"access_token"]) {
value = [CMCore get_access_token]?:@"";
}
//方法1
NSString *jsMethode = [NSString stringWithFormat:@"set_params('%@')",value];
[_web_view stringByEvaluatingJavaScriptFromString:jsMethode];
//方法2
// NSString *jsMethode = [NSString stringWithFormat:@"set_params('%@')",value];
// JSContext *context = [_web_view valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// [context evaluateScript:jsMethode];
//方法3
// [_bridge excuteJSWithObj:value function:paramsName];
}
分割线
第二种:利用第三方库实现JS与OC的相互传值。
- 1、 技术方案:使用
WebViewJavascriptBridge
三方库 - 2、 使用场景: 网页中代码中的某个方法,比如点击事件方法,将该方法的参数传值给OC,供OC使用。
- 3、
代码实现
如下:
oc给js传值
一、 JS里需要实现的代码(创建.js文件):
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
//调用上面定义的函数
setupWebViewJavascriptBridge(function (bridge){
//OC传值给JS 'testJavascriptHandler'为双方自定义好的统一方法名;'data'是OC传过来的值;'responseCallback'是JS接收到之后给OC的回调
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
//打印OC传过来的值
log('ObjC called testJavascriptHandler with', data)
var responseData = { 'Javascript Says':'Right back atcha!' }
log('JS responding with', responseData)
//给OC的回调
responseCallback(responseData)
})
二、OC里需要实现的代码:
- 1、导入第三方库
WebViewJavascriptBridge
;遵守UIWebViewDelegate
协议;
//设置第三方Bridge是否可用
[WebViewJavascriptBridge enableLogging];
//关联webView和bridge
_bridge = [WebViewJavascriptBridge bridgeForWebView:web];
[_bridge setWebViewDelegate:self];
//OC给JS传值,双方自定义一个统一的方法名'testJavascriptHandler';data里即为要传过去的值
[_bridge callHandler:@"testJavascriptHandler" data:@{@"年龄":@"20"}];
js给oc传值
一、创建js文件,js代码如下:
//点击网页上一个按钮时
callbackBt.onclick = function()
{
var str1=document.getElementById("text1").value;
var str2=document.getElementById("text2").value;
//JS给OC传值。'passValue'为双方自定义的统一方法名;'str1'&'str2'为要传的值; response为OC收到后给JS的回调
bridge.callHandler('passValue', {str1,str2}, function(response) {
})
}
二、oc要实现的代码
- 导入第三方库 WebViewJavascriptBridge;遵守UIWebViewDelegate协议;
//设置第三方Bridge是否可用
[WebViewJavascriptBridge enableLogging];
//关联webView和bridge
_bridge = [WebViewJavascriptBridge bridgeForWebView:web];
[_bridge setWebViewDelegate:self];
//js给oc传值.'passValue'为双方自定义的统一方法名;'data'为JS传过来的值;'responseCallback'为OC收到值后给JS返回的回调
[_bridge registerHandler:@"passValue" handler:^(id data, WVJBResponseCallback responseCallback) {
//打印js传过来的值
NSLog(@"%@", data);
//返回给js的值
responseCallback(@"收到了");
}];
网友评论