BridgeUtil.java
2.96 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.github.lzyzsd.jsbridge;
import android.content.Context;
import android.webkit.WebView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BridgeUtil {
final static String YY_OVERRIDE_SCHEMA = "yy://";
final static String YY_RETURN_DATA = YY_OVERRIDE_SCHEMA + "return/";//格式为 yy://return/{function}/returncontent
final static String YY_FETCH_QUEUE = YY_RETURN_DATA + "_fetchQueue/";
final static String EMPTY_STR = "";
final static String UNDERLINE_STR = "_";
final static String SPLIT_MARK = "/";
final static String CALLBACK_ID_FORMAT = "JAVA_CB_%s";
final static String JS_HANDLE_MESSAGE_FROM_JAVA = "javascript:WebViewJavascriptBridge._handleMessageFromNative(%s);";
final static String JS_FETCH_QUEUE_FROM_JAVA = "javascript:WebViewJavascriptBridge._fetchQueue();";
// public final static String JAVASCRIPT_STR = "javascript:";
public static final String JAVA_SCRIPT = "WebViewJavascriptBridge.js";
public final static String JAVASCRIPT_STR = "javascript:%s";
/**
* js 文件将注入为第一个script引用
* @param view WebView
* @param url url
*/
public static void webViewLoadJs(WebView view, String url){
String js = "var newscript = document.createElement(\"script\");";
js += "newscript.src=\"" + url + "\";";
js += "document.scripts[0].parentNode.insertBefore(newscript,document.scripts[0]);";
view.loadUrl("javascript:" + js);
}
/**
* 这里只是加载lib包中assets中的 WebViewJavascriptBridge.js
* @param view webview
* @param path 路径
*/
public static void webViewLoadLocalJs(WebView view, String path){
String jsContent = assetFile2Str(view.getContext(), path);
view.loadUrl("javascript:" + jsContent);
}
/**
* 解析assets文件夹里面的代码,去除注释,取可执行的代码
* @param c context
* @param urlStr 路径
* @return 可执行代码
*/
public static String assetFile2Str(Context c, String urlStr){
InputStream in = null;
try{
in = c.getAssets().open(urlStr);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
if (line != null && !line.matches("^\\s*\\/\\/.*")) { // 去除注释
sb.append(line);
}
} while (line != null);
bufferedReader.close();
in.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String getFunctionFromReturnUrl(String url) {
return "";
}
public static String getDataFromReturnUrl(String url) {
return "";
}
public static String parseFunctionName(String jsUrl) {
return "";
}
}