native 与 js 通信
原生 native 与 js 的通信主要应用于现在的 hybirdApp 混合应用中,主要解决的一些 h5 不能实现但是可以调用原生的功能的通信。
主要包含了,native 调用 js 、js 调用 native 的通信方式。
IOS 与 js 通信
1、通过获取 jsContext( JavaScript 的全局上下文 ) 来实现通信
ios 获取 jsContext ,执行某一个方法并且注入方法供js执行
// 获取到全局上下文
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NNSting *alert = @"alert('something')"
// 调用上下文的 alert 方法
[context evaluateScript:alert]
// 在上下文中注入了 call 方法,调用的时候触发 native 函数
context[@"call"] = *() {
NSArray *args = [JSContext currentArguments]
NSLog(@"message");
}
2、ios 通过 stringByEvalautingJavascriptFromString 方法来调用 全局上下文上面方法
// 调用全局的 alert 方法
webview.stringByEvaluatingJavaScriptFromString("alert('something')")
3、通过拦截请求实现 js 效用 ios
jsbridge://methodName?param1=value1¶m2=value2 // js 调用原生的一般传参格式。
ios 拦截请求
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:@"jsbridge"]) {
// parse the rest of the URL object and execute functions
}
}
andriod 与 js 通信
1、andriod 向全局上下文注入方法,供 h5 调用 native
// 向全局注入一个 method 方法,h5 调用的时候执行 native 操作 webView.addJavascriptInterface(new JSInterface(), "method");
2、andriod 调用全局上下文的方法
webView.loadUrl("javascript:alert('hello.')");
上面总常见的 native 和 js 通信的方法
下面介绍 jsbridge 的相关模型
jsbridge h5简单模型
/*
* 假设 native 向全局住了一个 __call 方法
* native 每次执行完成后回调 __callback 方法
* */
const _handlers = {};
window.__callback = (...args) => {
let [callBackMethod, ...params] = args
// 进行解析
if (typeof params === 'string') params = JSON.parse(params)
// 更具回调方法执行对应的回调
_handlers[callBackMethod](params)
delete _handlers[callBackMethod]
}
let id = 0
window.call = (...args) => {
id++
let [method, params, callback] = args
const callBackMethod = `${method}_${id}`
// 将回调注册到_handlers供__callback使用
_handlers[callBackMethod] = callback
params.callback = callBackMethod
// 调用相关的方法,传入参数
window.__call(method, JSON.stringify(params))
}
简单模型,更能看明白原理。