AgentWeb调用JsBridge采坑记录

AgentWeb:https://github.com/Justson/AgentWeb
JsBridge:https://github.com/lzyzsd/JsBridge

JS需添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function() {
callback(WebViewJavascriptBridge)
},
false
);
}
}

connectWebViewJavascriptBridge(function(bridge) {
bridge.init(function(message, responseCallback) {
console.log('Js got a message', message);
var data = {
'Javascript Responds': '测试中文!'
};
console.log('Js responding with', data);
responseCallback(data);
});
})

WebViewClient

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private WebViewClient getWebViewClient() {
return new WebViewClient() {
BridgeWebViewClient mBridgeWebViewClient = new BridgeWebViewClient(mBridgeWebView);

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
NLog.i(Constants.TAG, "url: " + request.getUrl().toString());
return mBridgeWebViewClient.shouldOverrideUrlLoading(view, request); //兼容高版本,必须设置
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
NLog.i(Constants.TAG, "url: " + url);
return mBridgeWebViewClient.shouldOverrideUrlLoading(view, url); //兼容低版本,必须设置
}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mBridgeWebViewClient.onPageStarted(view, url, favicon); //必须设置
}

@Override
public void onPageFinished(WebView view, String url) { //必须设置
mBridgeWebViewClient.onPageFinished(view, url);
}

@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
//yy://__QUEUE_MESSAGE__/
LogUtils.i(TAG, "onReceivedError:" + error.getDescription() + " code:" + error.getErrorCode() + ", url: " + request.getUrl().toString());
}
};
}

必须设置WebViewClient,并且其生命周期交由BridgeWebViewClient处理,否则报错:

1
agentweb - DefaultWebClient: onReceivedError:net::ERR_UNKNOWN_URL_SCHEME code:-10

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :