JSBridge的原理及使用

923 阅读1分钟

andorid原生调用js

// android 通过异步的方式执行js代码
webView.evaluateJavascript("javascript:方法名(‘参数1’,‘参数2’.....)",new ValueCallback(){
  @override
  public void onReceiveValue(String Value){
  
  }
})

js调用android原生

android代码

// 获取webView的设置对象 
WebSettings webSettings=webView.getSettings();

// 设置android 允许JS脚本
webSettings.setJavaScriptEnabled(true)

// 暴露一个叫JSBridge的对象到webviewde全局环境
webView.addJavascriptinterface(getJSBridge(),"JSBridge")

private Object getJSBridge(){
//实例化新对象
Object obj=new Object(){
@JavascriptInterface
//方法一
public String fun1(){
  return "fun1";
}
public String fun2(String param){
  return "fun2:"+param;
}
}
returm obj
}

js代码

window.JSBridge.fun1()
window.JSBridge.fun2("test1")

ios调用js

  1. 设置代理
  2. 实现代理方法
  3. 调用js
class ViewController: UIViewController,WKNavigationDelegate,WKScriptMessageHandler{
func webView(_ webView: WKWebView,didFinish navigation:WKNavigation!){
   webView.evaluateJavaScript("test()")
 }
}

js调用ios

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

WKUserContentController *userController = [[WKUserContentController alloc] init];
configuration.userContentController = userController;`
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];`

[userController addScriptMessageHandler:self name:@"deviceInfo"];`

(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {`
 
 if([message.name isEqualToString:@"deviceInfo"]) {`

  }
}

js代码

window.webkit.messageHandlers.deviceInfo.postMessage("");