本文采用第三方工具 WebViewJavascriptBridge
注冊監(jiān)聽事件
這段代碼是固定的酝惧,必須要放到j(luò)s中
/*這段代碼是固定的,必須要放到j(luò)s中*/
function setupWebViewJavascriptBridge(callback) {
//Android使用
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function() {
callback(WebViewJavascriptBridge)
},
false
);
}
//iOS使用
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)
}
原生調(diào)用js
在 setupWebViewJavascriptBridge 中注冊原生調(diào)用的js
//在改function 中添加原生調(diào)起js方法
setupWebViewJavascriptBridge(function(bridge) {
bridges = bridge;
//注冊原生調(diào)起方法
//參數(shù)1: buttonjs 注冊flag 供原生使用伯诬,要和原生統(tǒng)一
//參數(shù)2: data? 是原生傳給js 的數(shù)據(jù)
//參數(shù)3: responseCallback 是js 的回調(diào)晚唇,可以通過該方法給原生傳數(shù)據(jù)
bridge.registerHandler("buttonjs",function(data,responseCallback){
document.getElementById("show").innerHTML = "buuton js" + data;
responseCallback("button js callback");
});
})
js 調(diào)用原生方法
注:該方法應(yīng)放在setupWebViewJavascriptBridge 中進(jìn)行綁定
document.getElementById('enter3').onclick = function (e) {
var data = "good hello"
//參數(shù)1: pay 注冊flag 供原生使用,要和原生統(tǒng)一
//參數(shù)2: 是調(diào)起原生時向原生傳遞的參數(shù)
//參數(shù)3: 原生調(diào)用回調(diào)返回的數(shù)據(jù)
bridge.callHandler('getBlogNameFromObjC',data,function(resp){
document.getElementById("show").innerHTML = "payInterface" + resp;
}
);
完整代碼
js調(diào)用java
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function() {
callback(WebViewJavascriptBridge)
},
false
);
}
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)
}
//在改function 中添加原生調(diào)起js方法
setupWebViewJavascriptBridge(function(bridge) {
//注冊原生調(diào)起方法
//參數(shù)1: buttonjs 注冊flag 供原生使用盗似,要和原生統(tǒng)一
//參數(shù)2: data? 是原生傳給js 的數(shù)據(jù)
//參數(shù)3: responseCallback 是js 的回調(diào)哩陕,可以通過該方法給原生傳數(shù)據(jù)
bridge.registerHandler("getUserInfos",function(data,responseCallback){
document.getElementById("show").innerHTML = "buuton js" + data;
responseCallback("button js callback");
});
document.getElementById('enter3').onclick = function (e) {
var data = "hello"
//參數(shù)1: pay 注冊flag 供原生使用,要和原生統(tǒng)一
//參數(shù)2: 是調(diào)起原生時向原生傳遞的參數(shù)
//參數(shù)3: 原生調(diào)用回調(diào)返回的數(shù)據(jù)
bridge.callHandler('getBlogNameFromObjC',data,function(resp){
document.getElementById("show").innerHTML = "payInterface" + resp;
}
);
}
})
iOS方法使用
#import "JsBridgeViewController.h"
#import "WKWebViewJavascriptBridge.h"
#import "WebViewJavascriptBridge.h"
@interface JsBridgeViewController ()
@property(nonatomic,strong) WKWebViewJavascriptBridge* bridge;
@property (nonatomic, strong)WKWebView * wkWebView;
@end
@implementation JsBridgeViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.wkWebView];
[WKWebViewJavascriptBridge enableLogging];
self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.wkWebView];
[self.bridge setWebViewDelegate:self];
//OC端的注冊
//注冊jscalloc方法,js調(diào)用oc,data為oc回調(diào)給js的參數(shù)
[self.bridge registerHandler:@"getBlogNameFromObjC" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"js call getBlogNameFromObjC, data from js is %@", data);
if (responseCallback) {
// 反饋給JS
responseCallback(@{@"blogName": @"測試blog"});
}
}];
------------------------------------------------------------------
//OC端的調(diào)用
//調(diào)用js中注冊的showapiinner方法悍及,不傳入數(shù)據(jù)闽瓢,沒有回調(diào)
//[_bridge callHandler:@"showapiinner"];
//調(diào)用js中注冊的showapiinner方法,傳入數(shù)據(jù)str心赶,沒有回調(diào)
//[_bridge callHandler:@"showapiinner" data:str];
//調(diào)用js中注冊的showapiinner方法,傳入數(shù)據(jù)str缨叫,且有回調(diào)(可以獲取到回調(diào)參數(shù)responData)
// [_bridge callHandler:@"showapiinner" data:str responseCallback:^(id //responseData) {
// NSLog(@"%@",responseData);
// }];
[self renderButtons:self.wkWebView];
[self loadExamplePage:self.wkWebView];
}
//native調(diào)js? (native按鈕)
- (void)callHandler:(id)sender {
[self.bridge callHandler:@"getUserInfos" data:@{@"name": @"測試"} responseCallback:^(id responseData) {
NSLog(@"from js: %@", responseData);
}];
}
- (void)renderButtons:(WKWebView*)webView {
UIFont* font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
UIButton *callbackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[callbackButton setTitle:@"Call handler" forState:UIControlStateNormal];
[callbackButton addTarget:self action:@selector(callHandler:) forControlEvents:UIControlEventTouchUpInside];
[self.view insertSubview:callbackButton aboveSubview:webView];
callbackButton.frame = CGRectMake(10, 400, 100, 35);
callbackButton.titleLabel.font = font;
UIButton* reloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[reloadButton setTitle:@"Reload webview" forState:UIControlStateNormal];
[reloadButton addTarget:webView action:@selector(reload) forControlEvents:UIControlEventTouchUpInside];
[self.view insertSubview:reloadButton aboveSubview:webView];
reloadButton.frame = CGRectMake(110, 400, 100, 35);
reloadButton.titleLabel.font = font;
}
- (void)loadExamplePage:(WKWebView*)webView {
NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"demo0" ofType:@"html"];
NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
[webView loadHTMLString:appHtml baseURL:baseURL];
}
- (WKWebView *)wkWebView
{
if (!_wkWebView) {
_wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_wkWebView];
_wkWebView.navigationDelegate = self;
_wkWebView.scrollView.bounces = 0;
_wkWebView.scrollView.showsVerticalScrollIndicator = 0;
_wkWebView.scrollView.showsHorizontalScrollIndicator = 0;
}
return _wkWebView;
}
Android方法使用
package com.cfox.jsbridge;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import com.cfox.jsbridge.modle.User;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.Gson;
public class MainActivity extends AppCompatActivity {
private BridgeWebView mWebView;
ValueCallback mUploadMessage;
int RESULT_CODE = 0;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (BridgeWebView) findViewById(R.id.webView);
initWebView();
}
private void initWebView() {
mWebView.loadUrl("file:///android_asset/demo.html");
//js調(diào)native
mWebView.registerHandler("getBlogNameFromObjC", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Toast.makeText(MainActivity.this, "pay--->耻姥,"+ data, Toast.LENGTH_SHORT).show();
function.onCallBack("測試blog");
}
});
}
//native調(diào)js (native按鈕)
public void sendNative(View view) {
mWebView.callHandler("getUserInfos", "hello good", new CallBackFunction() {
@Override
public void onCallBack(String data) {
Toast.makeText(MainActivity.this, "buttonjs--->琐簇,"+ data, Toast.LENGTH_SHORT).show();
}
});
}
}