├── .gitignore
├── .gitlab-ci.yml
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── assets
│ ├── ExampleApp.html
│ └── js
│ │ └── ccnativeapi.js
│ ├── java
│ └── com
│ │ └── luffyjet
│ │ └── jsbridgeexample
│ │ ├── ImagesResult.java
│ │ ├── MainActivity.java
│ │ ├── NetworkStauts.java
│ │ ├── PathUtil.java
│ │ └── handlers
│ │ ├── DeviceInfoHandler.java
│ │ └── ImageChooseHandler.java
│ └── res
│ ├── layout
│ └── activity_main.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ ├── values-w820dp
│ └── dimens.xml
│ ├── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
│ └── xml
│ └── wjbconfig.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── assets
│ └── webviewjsbridge.js
│ └── java
│ └── com
│ └── luffyjet
│ └── webviewjavascriptbridge
│ ├── BridgeInterface.java
│ ├── ConfigXmlParser.java
│ ├── HandlerEntry.java
│ ├── HandlerManager.java
│ ├── JSResult.java
│ ├── RequestHandler.java
│ ├── Utils.java
│ ├── WebViewJavaScriptBridge.java
│ └── WebViewJavaScriptBridgeBase.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 | /app/build
11 | /library/build
12 |
13 |
--------------------------------------------------------------------------------
/.gitlab-ci.yml:
--------------------------------------------------------------------------------
1 | stages:
2 | - build
3 | - archive
4 |
5 | build_project:
6 | stage: build
7 | script:
8 | - gradle clean
9 |
10 | archive_project:
11 | stage: archive
12 | script:
13 | - gradle assembleRelease
14 | only:
15 | - master
16 | artifacts:
17 | paths:
18 | - app/build/outputs/apk/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2017 luffyjet
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | WebViewJavascriptBridge
2 | ==========================
3 | 根据[IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge) 编写而来的JavascriptBridge。
4 |
5 |
6 | 相比同类库的优点:
7 | 1. 和[IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge) 一样的使用方法,可共用一套JS代码。
8 | 2. 同时也在此之上做了加强,参考了Cordova源码的模块管理,方便把各种不同的原生功能封装成独立的模块并统一管理。具体请看下面的 模块管理功能一栏。
9 |
10 | 规定JS和Java之间用标准JSON格式字符串交互,JS传给Java的数据会封装成 org.json.JSONObject。
11 |
12 | (An Android bridge for sending messages between Java and JavaScript in WebViews. Based on [IOS marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge).)
13 |
14 |
15 | ### Gradle
16 |
17 |
18 | ```groovy
19 | repositories {
20 | jcenter()
21 | }
22 |
23 | compile 'com.luffyjet:webviewjavascriptbridge:1.0'
24 | ```
25 |
26 |
27 |
28 | Examples
29 | --------
30 |
31 | See the `app/` folder.
32 |
33 |
34 |
35 | Usage
36 | -----
37 |
38 | 1) Init WebViewJavaScriptBridge
39 |
40 | ```java
41 | WebSettings settings = webView.getSettings();
42 | settings.setJavaScriptEnabled(true);//很关键
43 | WebViewJavaScriptBridge mBridge = WebViewJavaScriptBridge.bridgeForWebView(this, webView);
44 | mBridge.setWebViewDelegate(new MyWebViewClient());//设置WebViewClient
45 | webView.setWebChromeClient(new MyChromeClient());//设置ChromeClient
46 | ```
47 |
48 | 2) Register a handler in Java, and call a JS handler:
49 |
50 | ```java
51 | //注册一个 处理 js端发来消息的 handler
52 | mBridge.registerHandler("abs", new WebViewJavaScriptBridgeBase.WVJBHandler() {
53 | @Override
54 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
55 | Log.d(TAG, "from JS req: " + data.toString());
56 | responseCallback.callback(new JSResult("i like milk from native").toJson());
57 | }
58 | });
59 |
60 | mBridge.callHandler("NativeCallJS", model.toJSON(), new WebViewJavaScriptBridgeBase.WVJBResponseCallback() {
61 | @Override
62 | public void callback(String responseData) {
63 | Log.d(TAG, "JS responded:" + responseData);
64 | Toast.makeText(MainActivity.this, "JS responded:" + responseData , Toast.LENGTH_SHORT).show();
65 | }
66 | });
67 |
68 | ```
69 |
70 | 3) Copy and paste `setupWebViewJavascriptBridge` into your JS:
71 |
72 | ```javascript
73 | function setupWebViewJavascriptBridge(callback) {
74 | if(window.WebViewJavascriptBridge) {
75 | return callback(WebViewJavascriptBridge);
76 | }
77 | if(window.WVJBCallbacks) {
78 | return window.WVJBCallbacks.push(callback);
79 | }
80 | window.WVJBCallbacks = [callback];
81 | var WVJBIframe = document.createElement('iframe');
82 | WVJBIframe.style.display = 'none';
83 | //这里最新IOS版是 https的scheme,真实环境下 需要判断iOS和Android,做下区分。
84 | WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
85 | document.documentElement.appendChild(WVJBIframe);
86 | setTimeout(function() {
87 | document.documentElement.removeChild(WVJBIframe)
88 | }, 0);
89 | }
90 | ```
91 |
92 | 5) Finally, call `setupWebViewJavascriptBridge` and then use the bridge to register handlers and call Java handlers:
93 |
94 | ```javascript
95 | setupWebViewJavascriptBridge(function(bridge) {
96 | /* Initialize your app here */
97 |
98 | bridge.registerHandler('NativeCallJS', function(data, responseCallback) {
99 | var responseData = {
100 | 'Javascript Says': 'Right back atcha!'
101 | };
102 |
103 | log('Native call JS with ', data);
104 | responseCallback(responseData);
105 | });
106 |
107 | var doc = document;
108 | var readyEvent = doc.createEvent('Events');
109 | readyEvent.initEvent('WebViewJavascriptBridgeReady');
110 | readyEvent.bridge = WebViewJavascriptBridge;
111 | doc.dispatchEvent(readyEvent);
112 | });
113 | ```
114 |
115 |
116 | ## 模块管理功能
117 | 可以和Cordova一样进行模块管理,同一种类型的消息(handler name相同)都由一个模块处理。
118 | 模块类需要继承 RequestHandler ,包含WebView的Activity要实现 BridgeInterface 接口。插件类由XML文件进行配置,请在项目中新建 res/xml/wjbconfig.xml 文件。
119 |
120 | ```java
121 |
122 |
123 |
124 |
127 |
130 |
131 |
132 |
133 |
136 |
139 |
140 |
141 |
142 |
143 |
144 | //一个简单的选图模块示例
145 | public class ImageChooseHandler extends RequestHandler {
146 | private static final String TAG = "ImageChooseHandler";
147 | private static final int REQUEST_CODE_IMAGES = 100;
148 | private WebViewJavaScriptBridgeBase.WVJBResponseCallback mResponseCallback;
149 |
150 | @Override
151 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
152 |
153 | mResponseCallback = responseCallback;
154 | ...
155 | mBridgeInterface.startActivityForResult(this, Intent.createChooser(i, "选取图片"), REQUEST_CODE_IMAGES);
156 | }
157 |
158 | @Override
159 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
160 | if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGES) {
161 | try {
162 | ...
163 | mResponseCallback.callback(result.toJSON());
164 | } catch (Exception e) {
165 | e.printStackTrace();
166 | }
167 | }
168 | }
169 | }
170 |
171 |
172 | // 包含webview 的 WebActivity
173 | public class WebActivity extends AppCompatActivity implements BridgeInterface{
174 |
175 | RequestHandler mRequestHandler;
176 |
177 | @Override
178 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
179 | super.onActivityResult(requestCode, resultCode, data);
180 | if (null != mRequestHandler) {
181 | RequestHandler callback = mRequestHandler;
182 | mRequestHandler = null;
183 | callback.onActivityResult(requestCode, resultCode, data);
184 | return;
185 | }
186 |
187 | //other code
188 | }
189 |
190 | @Override
191 | public void startActivityForResult(RequestHandler command, Intent intent, int requestCode) {
192 | setActivityResultCallback(command);
193 | startActivityForResult(intent, requestCode);
194 | }
195 |
196 | @Override
197 | public void setActivityResultCallback(RequestHandler plugin) {
198 | mRequestHandler = plugin;
199 | }
200 |
201 | @Override
202 | public Activity getActivity() {
203 | return this;
204 | }
205 |
206 | @Override
207 | public ExecutorService getThreadPool() {
208 | return Executors.newCachedThreadPool(new ThreadFactory() {
209 | @Override
210 | public Thread newThread(final Runnable r) {
211 | return new Thread(new Runnable() {
212 | @Override
213 | public void run() {
214 | android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
215 | r.run();
216 | }
217 | },"Test");
218 | }
219 | });
220 | }
221 | }
222 |
223 | ```
224 |
225 | 一个功能模块对应一个feature,feature name就是handle name。 onload属性为true代表模块(插件)会在webview初始化时一同初始化,false则是在需要该模块(插件)的时候通过反射加载。
226 |
227 | 具体使用方法请查看 ``app/`` 目录下的示例代码。
228 |
229 |
230 | ## Thanks
231 | [marcuswestin/WebViewJavascriptBridge](https://github.com/marcuswestin/WebViewJavascriptBridge)
232 | & [lzyzsd/JsBridge](https://github.com/lzyzsd/JsBridge) & [cordova-android](https://github.com/apache/cordova-android)
233 |
234 |
235 |
236 | License
237 | --------
238 |
239 | See the [LICENSE](https://github.com/luffyjet/WebViewJavaScriptBridge/blob/master/LICENSE.md) file for license rights and limitations.
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion Integer.parseInt(rootProject.android_compileSdkVersion)
5 | buildToolsVersion rootProject.android_buildToolsVersion
6 |
7 | defaultConfig {
8 | applicationId rootProject.example_package
9 | minSdkVersion Integer.parseInt(rootProject.android_minSdkVersion)
10 | targetSdkVersion Integer.parseInt(rootProject.android_targetSdkVersion)
11 | versionCode Integer.parseInt(rootProject.android_versionCode)
12 | versionName rootProject.android_versionName
13 | }
14 |
15 |
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | compile fileTree(dir: 'libs', include: ['*.jar'])
26 | compile "com.android.support:appcompat-v7:${android_support}"
27 | compile "com.google.code.gson:gson:${android_gson}"
28 | // compile project(':library')
29 | compile 'com.luffyjet:webviewjavascriptbridge:1.0'
30 | }
31 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/luffyjet/Documents/android-sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
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 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/app/src/main/assets/ExampleApp.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
30 |
31 |
32 |
33 |
90 |
91 |
92 |
93 |
WebViewJavascriptBridge Demo
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
--------------------------------------------------------------------------------
/app/src/main/assets/js/ccnativeapi.js:
--------------------------------------------------------------------------------
1 | ;(function() {
2 | window.onerror = function(err) {
3 | console.log("page on error:" + err);
4 | };
5 |
6 | var browserType = {
7 | types: function() {
8 | var u = window.navigator.userAgent,
9 | app = window.navigator.appVersion;
10 | return { //移动终端浏览器版本信息
11 | trident: u.indexOf('Trident') > -1, //IE内核
12 | presto: u.indexOf('Presto') > -1, //opera内核
13 | webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
14 | gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
15 | mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
16 | mac: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
17 | android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
18 | iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
19 | iPad: u.indexOf('iPad') > -1, //是否iPad
20 | webApp: u.indexOf('Safari') == -1 //是否web应该程序,没有头部与底部
21 |
22 | };
23 | }(),
24 |
25 | language: (window.navigator.browserLanguage || window.navigator.language).toLowerCase()
26 | };
27 |
28 | function setupWebViewJavascriptBridge(callback) {
29 | if(window.WebViewJavascriptBridge) {
30 | return callback(WebViewJavascriptBridge);
31 | }
32 | if(window.WVJBCallbacks) {
33 | return window.WVJBCallbacks.push(callback);
34 | }
35 | window.WVJBCallbacks = [callback];
36 | var WVJBIframe = document.createElement('iframe');
37 | WVJBIframe.style.display = 'none';
38 | if(browserType.types.android) {
39 | WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
40 | } else if(browserType.types.mac || browserType.types.iPhone || browserType.types.iPad) {
41 | WVJBIframe.src = 'https://__bridge_loaded__';
42 | }
43 | document.documentElement.appendChild(WVJBIframe);
44 | setTimeout(function() {
45 | document.documentElement.removeChild(WVJBIframe)
46 | }, 0);
47 | }
48 |
49 | function invoke(handlerName, data, callback) {
50 | if(window.WebViewJavascriptBridge) {
51 | window.WebViewJavascriptBridge.callHandler(handlerName, data, callback);
52 | } else {
53 | document.addEventListener(
54 | 'WebViewJavascriptBridgeReady',
55 | function() {
56 | window.WebViewJavascriptBridge.callHandler(handlerName, data, callback);
57 | },
58 | false
59 | );
60 | }
61 | }
62 |
63 | setupWebViewJavascriptBridge(function(bridge) {
64 | bridge.registerHandler('NativeCallJS', function(data, responseCallback) {
65 | var responseData = {
66 | 'Javascript Says': 'Right back atcha!'
67 | };
68 |
69 | log('Native call JS with ', data);
70 | responseCallback(responseData);
71 | });
72 |
73 | var doc = document;
74 | var readyEvent = doc.createEvent('Events');
75 | readyEvent.initEvent('WebViewJavascriptBridgeReady');
76 | readyEvent.bridge = WebViewJavascriptBridge;
77 | doc.dispatchEvent(readyEvent);
78 | });
79 |
80 |
81 | window.ccapi = {
82 | //设备信息
83 | deviceInfo: function(data) {
84 | invoke("deviceInfo", {
85 | 'full': data.full
86 | }, data.success);
87 | },
88 |
89 | //选择图片
90 | chooseImage: function(data) {
91 | invoke("chooseImage", {
92 | 'count': data.count,
93 | 'sizeType': data.sizeType,
94 | 'sourceType': data.sourceType
95 | }, data.success);
96 | }
97 |
98 | };
99 | })();
--------------------------------------------------------------------------------
/app/src/main/java/com/luffyjet/jsbridgeexample/ImagesResult.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.jsbridgeexample;
2 |
3 | import com.google.gson.Gson;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * Title :
9 | * Author : luffyjet
10 | * Date : 2016/12/20
11 | * Project : branch_1009
12 | * Site : http://www.luffyjet.com
13 | */
14 |
15 | public class ImagesResult {
16 | public List localIds;
17 | public boolean status;
18 | public ImagesResult(boolean b) {
19 | status = b;
20 | }
21 |
22 | public String toJSON() {
23 | return new Gson().toJson(this);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/luffyjet/jsbridgeexample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.jsbridgeexample;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.graphics.Bitmap;
6 | import android.net.Uri;
7 | import android.os.Bundle;
8 | import android.os.Process;
9 | import android.support.v7.app.AppCompatActivity;
10 | import android.util.Log;
11 | import android.view.View;
12 | import android.webkit.ValueCallback;
13 | import android.webkit.WebChromeClient;
14 | import android.webkit.WebSettings;
15 | import android.webkit.WebView;
16 | import android.webkit.WebViewClient;
17 | import android.widget.Button;
18 | import android.widget.Toast;
19 |
20 | import com.google.gson.Gson;
21 | import com.luffyjet.webviewjavascriptbridge.BridgeInterface;
22 | import com.luffyjet.webviewjavascriptbridge.JSResult;
23 | import com.luffyjet.webviewjavascriptbridge.RequestHandler;
24 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridge;
25 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridgeBase;
26 |
27 | import org.json.JSONObject;
28 |
29 | import java.util.concurrent.ExecutorService;
30 | import java.util.concurrent.Executors;
31 | import java.util.concurrent.ThreadFactory;
32 |
33 | public class MainActivity extends AppCompatActivity implements BridgeInterface{
34 | private static final String TAG = MainActivity.class.getSimpleName();
35 | WebViewJavaScriptBridge mBridge;
36 | RequestHandler mRequestHandler;
37 |
38 | @Override
39 | protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | setContentView(R.layout.activity_main);
42 | initView();
43 | }
44 |
45 | private void initView() {
46 | if (mBridge != null) {
47 | return;
48 | }
49 |
50 | final WebView webView = (WebView) findViewById(R.id.webview);
51 | Button callJsBtn = (Button) findViewById(R.id.button);
52 | Button disableTimeoutBtn = (Button) findViewById(R.id.disable_timeout);
53 | Button refreshBtn = (Button) findViewById(R.id.refresh);
54 |
55 |
56 | //Start 初始化 WebViewJavaScriptBridge
57 | WebViewJavaScriptBridge.enableLogging();//打印Log
58 | WebSettings settings = webView.getSettings();
59 | settings.setJavaScriptEnabled(true);//很关键
60 | mBridge = WebViewJavaScriptBridge.bridgeForWebView(this, webView);
61 | mBridge.setWebViewDelegate(new MyWebViewClient());//设置WebViewClient
62 | webView.setWebChromeClient(new MyChromeClient());//设置ChromeClient
63 | //End
64 |
65 |
66 | callJsBtn.setOnClickListener(new View.OnClickListener() {
67 | @Override
68 | public void onClick(View v) {
69 | //向js端发送消息
70 | callHandler();
71 | }
72 | });
73 |
74 | //注册一个 处理 js端发来消息的 handler
75 | mBridge.registerHandler("abs", new WebViewJavaScriptBridgeBase.WVJBHandler() {
76 | @Override
77 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
78 | Log.d(TAG, "from JS req: " + data.toString());
79 | responseCallback.callback(new JSResult("i like milk from native").toJson());
80 | }
81 | });
82 |
83 |
84 | disableTimeoutBtn.setOnClickListener(new View.OnClickListener() {
85 | @Override
86 | public void onClick(View v) {
87 | disableSafetyTimeout();
88 | }
89 | });
90 |
91 | refreshBtn.setOnClickListener(new View.OnClickListener() {
92 | @Override
93 | public void onClick(View v) {
94 | webView.reload();
95 | }
96 | });
97 |
98 | // webView.loadUrl("http://192.168.118.55:8090/spittr/ExampleApp.html");
99 |
100 | webView.loadUrl("file:///android_asset/ExampleApp.html");
101 | }
102 |
103 | @Override
104 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
105 | super.onActivityResult(requestCode, resultCode, data);
106 | if (null != mRequestHandler) {
107 | RequestHandler callback = mRequestHandler;
108 | mRequestHandler = null;
109 | callback.onActivityResult(requestCode, resultCode, data);
110 | return;
111 | }
112 |
113 | //other code
114 | }
115 |
116 | @Override
117 | public void startActivityForResult(RequestHandler command, Intent intent, int requestCode) {
118 | setActivityResultCallback(command);
119 | startActivityForResult(intent, requestCode);
120 | }
121 |
122 | @Override
123 | public void setActivityResultCallback(RequestHandler plugin) {
124 | mRequestHandler = plugin;
125 | }
126 |
127 | @Override
128 | public Activity getActivity() {
129 | return this;
130 | }
131 |
132 | @Override
133 | public ExecutorService getThreadPool() {
134 | return Executors.newCachedThreadPool(new ThreadFactory() {
135 | @Override
136 | public Thread newThread(final Runnable r) {
137 | return new Thread(new Runnable() {
138 | @Override
139 | public void run() {
140 | android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
141 | r.run();
142 | }
143 | },"Test");
144 | }
145 | });
146 | }
147 |
148 |
149 | /**
150 | * 发送消息给JS端
151 | */
152 | void callHandler() {
153 | Model model = new Model();
154 | model.name = "lucy";
155 | model.age = 18;
156 | model.msg = "Hi there, JS!";
157 |
158 | mBridge.callHandler("NativeCallJS", model.toJSON(), new WebViewJavaScriptBridgeBase.WVJBResponseCallback() {
159 | @Override
160 | public void callback(String responseData) {
161 | Log.d(TAG, "JS responded:" + responseData);
162 | Toast.makeText(MainActivity.this, "JS responded:" + responseData , Toast.LENGTH_SHORT).show();
163 | }
164 | });
165 | }
166 |
167 | void disableSafetyTimeout() {
168 | mBridge.disableJavscriptAlertBoxSafetyTimeout();
169 | }
170 |
171 | class MyChromeClient extends WebChromeClient {
172 |
173 | // Android < 3.0
174 | public void openFileChooser(ValueCallback uploadMsg) {
175 | //choose image or take photo
176 | }
177 |
178 | // Android > 3.0
179 | public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
180 | openFileChooser(uploadMsg);
181 | }
182 |
183 | // Android > 4.1.1
184 | public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
185 | openFileChooser(uploadMsg);
186 | }
187 |
188 | //Android >= 5.0
189 | @Override
190 | public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
191 | //choose image or take photo
192 | return true;
193 | }
194 | }
195 |
196 | class MyWebViewClient extends WebViewClient {
197 | @Override
198 | public void onPageStarted(WebView view, String url, Bitmap favicon) {
199 | super.onPageStarted(view, url, favicon);
200 | Log.i(TAG, "onPageStarted");
201 | }
202 |
203 |
204 | @Override
205 | public void onPageFinished(WebView view, String url) {
206 | super.onPageFinished(view, url);
207 | Log.i(TAG, "onPageFinished");
208 | }
209 |
210 |
211 | @Override
212 | public boolean shouldOverrideUrlLoading(WebView view, String url) {
213 | Log.i(TAG, "shouldOverrideUrlLoading");
214 | return super.shouldOverrideUrlLoading(view, url);
215 | }
216 | }
217 |
218 | static class Model {
219 | String name;
220 | int age;
221 | String msg;
222 |
223 | @Override
224 | public String toString() {
225 | return toJSON();
226 | }
227 |
228 | public String toJSON() {
229 | return new Gson().toJson(this);
230 | }
231 | }
232 |
233 | }
234 |
--------------------------------------------------------------------------------
/app/src/main/java/com/luffyjet/jsbridgeexample/NetworkStauts.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.jsbridgeexample;
2 |
3 | import android.content.Context;
4 | import android.net.ConnectivityManager;
5 | import android.net.NetworkInfo;
6 | import android.telephony.TelephonyManager;
7 |
8 |
9 | public class NetworkStauts {
10 | private static final int NETWORK_TYPE_UNAVAILABLE = -1;
11 | private static final int NETWORK_TYPE_WIFI = -101;
12 |
13 | private static final int NETWORK_CLASS_WIFI = -101;
14 | private static final int NETWORK_CLASS_UNAVAILABLE = -1;
15 | /** Unknown network class. */
16 | private static final int NETWORK_CLASS_UNKNOWN = 0;
17 | /** Class of broadly defined "2G" networks. */
18 | private static final int NETWORK_CLASS_2_G = 1;
19 | /** Class of broadly defined "3G" networks. */
20 | private static final int NETWORK_CLASS_3_G = 2;
21 | /** Class of broadly defined "4G" networks. */
22 | private static final int NETWORK_CLASS_4_G = 3;
23 |
24 | // 适配低版本手机
25 | /** Network type is unknown */
26 | public static final int NETWORK_TYPE_UNKNOWN = 0;
27 | /** Current network is GPRS */
28 | public static final int NETWORK_TYPE_GPRS = 1;
29 | /** Current network is EDGE */
30 | public static final int NETWORK_TYPE_EDGE = 2;
31 | /** Current network is UMTS */
32 | public static final int NETWORK_TYPE_UMTS = 3;
33 | /** Current network is CDMA: Either IS95A or IS95B */
34 | public static final int NETWORK_TYPE_CDMA = 4;
35 | /** Current network is EVDO revision 0 */
36 | public static final int NETWORK_TYPE_EVDO_0 = 5;
37 | /** Current network is EVDO revision A */
38 | public static final int NETWORK_TYPE_EVDO_A = 6;
39 | /** Current network is 1xRTT */
40 | public static final int NETWORK_TYPE_1xRTT = 7;
41 | /** Current network is HSDPA */
42 | public static final int NETWORK_TYPE_HSDPA = 8;
43 | /** Current network is HSUPA */
44 | public static final int NETWORK_TYPE_HSUPA = 9;
45 | /** Current network is HSPA */
46 | public static final int NETWORK_TYPE_HSPA = 10;
47 | /** Current network is iDen */
48 | public static final int NETWORK_TYPE_IDEN = 11;
49 | /** Current network is EVDO revision B */
50 | public static final int NETWORK_TYPE_EVDO_B = 12;
51 | /** Current network is LTE */
52 | public static final int NETWORK_TYPE_LTE = 13;
53 | /** Current network is eHRPD */
54 | public static final int NETWORK_TYPE_EHRPD = 14;
55 | /** Current network is HSPA+ */
56 | public static final int NETWORK_TYPE_HSPAP = 15;
57 |
58 |
59 | /**
60 | * 获取网络类型
61 | * @return
62 | */
63 | public static String getCurrentNetworkType(Context context) {
64 | int networkClass = getNetworkClass(context);
65 | String type = "unknown";
66 | switch (networkClass) {
67 | case NETWORK_CLASS_UNAVAILABLE:
68 | type = "none";
69 | break;
70 | case NETWORK_CLASS_WIFI:
71 | type = "Wi-Fi";
72 | break;
73 | case NETWORK_CLASS_2_G:
74 | type = "2G";
75 | break;
76 | case NETWORK_CLASS_3_G:
77 | type = "3G";
78 | break;
79 | case NETWORK_CLASS_4_G:
80 | type = "4G";
81 | break;
82 | case NETWORK_CLASS_UNKNOWN:
83 | type = "unknown";
84 | break;
85 | }
86 | return type;
87 | }
88 |
89 | private static int getNetworkClassByType(int networkType) {
90 | switch (networkType) {
91 | case NETWORK_TYPE_UNAVAILABLE:
92 | return NETWORK_CLASS_UNAVAILABLE;
93 | case NETWORK_TYPE_WIFI:
94 | return NETWORK_CLASS_WIFI;
95 | case NETWORK_TYPE_GPRS:
96 | case NETWORK_TYPE_EDGE:
97 | case NETWORK_TYPE_CDMA:
98 | case NETWORK_TYPE_1xRTT:
99 | case NETWORK_TYPE_IDEN:
100 | return NETWORK_CLASS_2_G;
101 | case NETWORK_TYPE_UMTS:
102 | case NETWORK_TYPE_EVDO_0:
103 | case NETWORK_TYPE_EVDO_A:
104 | case NETWORK_TYPE_HSDPA:
105 | case NETWORK_TYPE_HSUPA:
106 | case NETWORK_TYPE_HSPA:
107 | case NETWORK_TYPE_EVDO_B:
108 | case NETWORK_TYPE_EHRPD:
109 | case NETWORK_TYPE_HSPAP:
110 | return NETWORK_CLASS_3_G;
111 | case NETWORK_TYPE_LTE:
112 | return NETWORK_CLASS_4_G;
113 | default:
114 | return NETWORK_CLASS_UNKNOWN;
115 | }
116 | }
117 |
118 |
119 | private static int getNetworkClass(Context context) {
120 | int networkType = NETWORK_TYPE_UNKNOWN;
121 | try {
122 | final NetworkInfo network = ((ConnectivityManager) context
123 | .getSystemService(Context.CONNECTIVITY_SERVICE))
124 | .getActiveNetworkInfo();
125 | if (network != null && network.isAvailable()
126 | && network.isConnected()) {
127 | int type = network.getType();
128 | if (type == ConnectivityManager.TYPE_WIFI) {
129 | networkType = NETWORK_TYPE_WIFI;
130 | } else if (type == ConnectivityManager.TYPE_MOBILE) {
131 | TelephonyManager telephonyManager = (TelephonyManager) context
132 | .getSystemService(Context.TELEPHONY_SERVICE);
133 | networkType = telephonyManager.getNetworkType();
134 | }
135 | } else {
136 | networkType = NETWORK_TYPE_UNAVAILABLE;
137 | }
138 |
139 | } catch (Exception ex) {
140 | ex.printStackTrace();
141 | }
142 | return getNetworkClassByType(networkType);
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/app/src/main/java/com/luffyjet/jsbridgeexample/PathUtil.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.jsbridgeexample;
2 |
3 | import android.annotation.TargetApi;
4 | import android.app.Activity;
5 | import android.content.ContentUris;
6 | import android.content.Context;
7 | import android.database.Cursor;
8 | import android.net.Uri;
9 | import android.os.Environment;
10 | import android.provider.DocumentsContract;
11 | import android.provider.MediaStore;
12 |
13 | public class PathUtil {
14 | /**
15 | * 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
16 | * @param context
17 | * @param imageUri
18 | * @author yaoxing
19 | * @date 2014-10-12
20 | */
21 | @TargetApi(19)
22 | public static String getImageAbsolutePath(Activity context, Uri imageUri) {
23 | if (context == null || imageUri == null)
24 | return null;
25 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
26 | if (isExternalStorageDocument(imageUri)) {
27 | String docId = DocumentsContract.getDocumentId(imageUri);
28 | String[] split = docId.split(":");
29 | String type = split[0];
30 | if ("primary".equalsIgnoreCase(type)) {
31 | return Environment.getExternalStorageDirectory() + "/" + split[1];
32 | }
33 | } else if (isDownloadsDocument(imageUri)) {
34 | String id = DocumentsContract.getDocumentId(imageUri);
35 | Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
36 | return getDataColumn(context, contentUri, null, null);
37 | } else if (isMediaDocument(imageUri)) {
38 | String docId = DocumentsContract.getDocumentId(imageUri);
39 | String[] split = docId.split(":");
40 | String type = split[0];
41 | Uri contentUri = null;
42 | if ("image".equals(type)) {
43 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
44 | } else if ("video".equals(type)) {
45 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
46 | } else if ("audio".equals(type)) {
47 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
48 | }
49 | String selection = MediaStore.Images.Media._ID + "=?";
50 | String[] selectionArgs = new String[]{split[1]};
51 | return getDataColumn(context, contentUri, selection, selectionArgs);
52 | }
53 | } // MediaStore (and general)
54 | else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
55 | // Return the remote address
56 | if (isGooglePhotosUri(imageUri))
57 | return imageUri.getLastPathSegment();
58 | return getDataColumn(context, imageUri, null, null);
59 | }
60 | // File
61 | else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
62 | return imageUri.getPath();
63 | }
64 | return null;
65 | }
66 |
67 | public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
68 | Cursor cursor = null;
69 | String column = MediaStore.Images.Media.DATA;
70 | String[] projection = {column};
71 | try {
72 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
73 | if (cursor != null && cursor.moveToFirst()) {
74 | int index = cursor.getColumnIndexOrThrow(column);
75 | return cursor.getString(index);
76 | }
77 | } finally {
78 | if (cursor != null)
79 | cursor.close();
80 | }
81 | return null;
82 | }
83 |
84 | /**
85 | * @param uri The Uri to check.
86 | * @return Whether the Uri authority is ExternalStorageProvider.
87 | */
88 | public static boolean isExternalStorageDocument(Uri uri) {
89 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
90 | }
91 |
92 | /**
93 | * @param uri The Uri to check.
94 | * @return Whether the Uri authority is DownloadsProvider.
95 | */
96 | public static boolean isDownloadsDocument(Uri uri) {
97 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
98 | }
99 |
100 | /**
101 | * @param uri The Uri to check.
102 | * @return Whether the Uri authority is MediaProvider.
103 | */
104 | public static boolean isMediaDocument(Uri uri) {
105 | return "com.android.providers.media.documents".equals(uri.getAuthority());
106 | }
107 |
108 | /**
109 | * @param uri The Uri to check.
110 | * @return Whether the Uri authority is Google Photos.
111 | */
112 | public static boolean isGooglePhotosUri(Uri uri) {
113 | return "com.google.android.apps.photos.content".equals(uri.getAuthority());
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/app/src/main/java/com/luffyjet/jsbridgeexample/handlers/DeviceInfoHandler.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.jsbridgeexample.handlers;
2 |
3 | import android.content.Context;
4 | import android.content.pm.PackageInfo;
5 | import android.content.pm.PackageManager;
6 | import android.os.Build;
7 | import android.telephony.TelephonyManager;
8 |
9 | import com.google.gson.Gson;
10 | import com.luffyjet.jsbridgeexample.NetworkStauts;
11 | import com.luffyjet.jsbridgeexample.R;
12 | import com.luffyjet.webviewjavascriptbridge.RequestHandler;
13 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridgeBase;
14 |
15 | import org.json.JSONObject;
16 |
17 | /**
18 | * Title :
19 | * Author : luffyjet
20 | * Date : 2016/12/19
21 | * Project : WebViewJavaScriptBridge
22 | * Site : http://www.luffyjet.com
23 | */
24 |
25 | public class DeviceInfoHandler extends RequestHandler {
26 |
27 | @Override
28 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
29 | log(getHandlerName(), data.toString());
30 | responseCallback.callback(new DeviceInfo().toJson(mContext));
31 | }
32 |
33 |
34 | private static class DeviceInfo {
35 |
36 | String appName;//应用名称
37 | String appVersion;//CC+版本号
38 | String systemType;//系统类型
39 | String systemVersion;//版本
40 | String version;//JS桥接引擎版本
41 | String deviceModel;//设备型号,字符串类型
42 | String deviceName;//设备名称,字符串类型
43 | String operator;//运营商名称,若未获取到则返回none,字符串类型
44 |
45 | /**
46 | * 网络类型,字符串类型
47 | *
48 | * unknown //未知
49 | * wifi //wifi
50 | * 2g //2G网络
51 | * 3g //3G网络
52 | * 4g //4G网络
53 | * none //无网络
54 | */
55 | public String connectionType;//
56 |
57 |
58 | String toJson(Context context) {
59 | try {
60 | appName = context.getString(R.string.app_name);
61 | systemType = "Android";
62 | systemVersion = Build.VERSION.RELEASE;
63 | version = "1.0";
64 | deviceModel = Build.MODEL;
65 | deviceName = Build.PRODUCT;
66 |
67 | PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
68 | appVersion = pi.versionName;
69 |
70 | TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
71 | operator = telephonyManager.getSimOperatorName();
72 |
73 | connectionType = NetworkStauts.getCurrentNetworkType(context);
74 | } catch (PackageManager.NameNotFoundException e) {
75 | e.printStackTrace();
76 | }
77 |
78 | return new Gson().toJson(this);
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/app/src/main/java/com/luffyjet/jsbridgeexample/handlers/ImageChooseHandler.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.jsbridgeexample.handlers;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.util.Log;
6 |
7 | import com.luffyjet.jsbridgeexample.ImagesResult;
8 | import com.luffyjet.jsbridgeexample.PathUtil;
9 | import com.luffyjet.webviewjavascriptbridge.RequestHandler;
10 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridge;
11 | import com.luffyjet.webviewjavascriptbridge.WebViewJavaScriptBridgeBase;
12 |
13 | import org.json.JSONObject;
14 |
15 | import java.util.ArrayList;
16 | import java.util.List;
17 |
18 | /**
19 | * Title :
20 | * Author : luffyjet
21 | * Date : 2016/12/16
22 | * Project : WebViewJavaScriptBridge
23 | * Site : http://www.luffyjet.com
24 | */
25 |
26 | public class ImageChooseHandler extends RequestHandler {
27 | private static final String TAG = "ImageChooseHandler";
28 | private static final int REQUEST_CODE_IMAGES = 100;
29 | private WebViewJavaScriptBridgeBase.WVJBResponseCallback mResponseCallback;
30 |
31 | @Override
32 | public void handle(JSONObject data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
33 | log(getHandlerName(), data.toString());
34 | mResponseCallback = responseCallback;
35 |
36 | int count = 0;
37 |
38 | try {
39 | count = data.optInt("count");
40 | } catch (Exception e) {
41 | e.printStackTrace();
42 | }
43 |
44 | if (count == 0) {
45 | count = 9;
46 | }
47 |
48 | //这里只选取一张,真实情况下,可以通过自定义的选图界面,选择复数的图片,并返回给JS
49 | Intent i = new Intent(Intent.ACTION_GET_CONTENT);
50 | i.addCategory(Intent.CATEGORY_OPENABLE);
51 | i.setType("image/*");
52 | mBridgeInterface.startActivityForResult(this, Intent.createChooser(i, "选取图片"), REQUEST_CODE_IMAGES);
53 | }
54 |
55 | @Override
56 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
57 | if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGES) {
58 | Log.i(TAG, "onActivityResult: " + data.getData());
59 | try {
60 | //根据Uri 获取真实路径
61 | String path = PathUtil.getImageAbsolutePath(mBridgeInterface.getActivity(), data.getData());
62 | Log.i(TAG, "onActivityResult: " + path);
63 | ImagesResult result = new ImagesResult(true);
64 | List ids = new ArrayList<>();
65 | //在真实路径之前添加特殊SCHEMA,在WebViewClient.shouldInterceptRequest方法里做资源替换,将图片显示出来
66 | //具体可查看WebViewJavaScriptBridge的源码
67 | ids.add(WebViewJavaScriptBridge.LOCAL_FILE_SCHEMA + path);
68 | result.localIds = ids;
69 | mResponseCallback.callback(result.toJSON());
70 |
71 | } catch (Exception e) {
72 | e.printStackTrace();
73 | }
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
16 |
17 |
20 |
21 |
27 |
28 |
34 |
35 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/luffyjet/WebViewJavaScriptBridge/d1400d0d10e0c0d24b15482f0073ac4bb590c6a7/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/luffyjet/WebViewJavaScriptBridge/d1400d0d10e0c0d24b15482f0073ac4bb590c6a7/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/luffyjet/WebViewJavaScriptBridge/d1400d0d10e0c0d24b15482f0073ac4bb590c6a7/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/luffyjet/WebViewJavaScriptBridge/d1400d0d10e0c0d24b15482f0073ac4bb590c6a7/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/luffyjet/WebViewJavaScriptBridge/d1400d0d10e0c0d24b15482f0073ac4bb590c6a7/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | JSBridgeExample
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/wjbconfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
10 |
11 |
12 |
13 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | // jcenter()
6 | maven {
7 | url 'http://maven.aliyun.com/nexus/content/groups/public/'
8 | }
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:2.2.3'
12 | classpath 'com.novoda:bintray-release:0.4.0'
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | // jcenter()
21 | maven {
22 | url 'http://maven.aliyun.com/nexus/content/groups/public/'
23 | }
24 | }
25 | }
26 |
27 | task clean(type: Delete) {
28 | delete rootProject.buildDir
29 | }
30 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | org.gradle.daemon=true
18 | org.gradle.parallel=true
19 |
20 | example_package = com.luffyjet.jsbridgeexample
21 |
22 | android_compileSdkVersion=23
23 | android_buildToolsVersion = 23.0.3
24 | android_support = 23.0.1
25 |
26 | android_minSdkVersion =9
27 | android_targetSdkVersion =22
28 | android_versionCode = 1
29 | android_versionName = 1.0
30 | android_gson = 2.4
31 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/luffyjet/WebViewJavaScriptBridge/d1400d0d10e0c0d24b15482f0073ac4bb590c6a7/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 | android {
4 | compileSdkVersion Integer.parseInt(rootProject.android_compileSdkVersion)
5 | buildToolsVersion rootProject.android_buildToolsVersion
6 |
7 | defaultConfig {
8 | minSdkVersion Integer.parseInt(rootProject.android_minSdkVersion)
9 | targetSdkVersion Integer.parseInt(rootProject.android_targetSdkVersion)
10 | versionCode Integer.parseInt(rootProject.android_versionCode)
11 | versionName rootProject.android_versionName
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | compile fileTree(dir: 'libs', include: ['*.jar'])
23 |
24 | }
25 |
26 | publish {
27 | userOrg = 'luffyjetx'
28 | groupId = 'com.luffyjet'
29 | artifactId = 'webviewjavascriptbridge'
30 | publishVersion = '1.0'
31 | desc = 'android webview javascript bridge'
32 | website = 'https://github.com/luffyjet/webviewjavascriptbridge'
33 | licences = ['Apache-2.0']
34 | }
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/luffyjet/Documents/android-sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/library/src/main/assets/webviewjsbridge.js:
--------------------------------------------------------------------------------
1 | ;(function() {
2 | if(window.WebViewJavascriptBridge) {
3 | return;
4 | }
5 |
6 | if(!window.onerror) {
7 | window.onerror = function(msg, url, line) {
8 | console.log("WebViewJavascriptBridge: ERROR:" + msg + "@" + url + ":" + line);
9 | }
10 | }
11 |
12 | var messagingIframe;
13 | var sendMessageQueue = [];
14 | var messageHandlers = {};
15 |
16 | var CUSTOM_PROTOCOL_SCHEME = 'wvjbscheme';
17 | var QUEUE_HAS_MESSAGE = '__WVJB_QUEUE_MESSAGE__';
18 | var QUEUE_RETURN_MESSAGE = '__WVJB_RETURN_MESSAGE__';
19 |
20 | var responseCallbacks = {};
21 | var uniqueId = 1;
22 | var dispatchMessagesWithTimeoutSafety = true;
23 |
24 | function registerHandler(handlerName, handler) {
25 | messageHandlers[handlerName] = handler;
26 | }
27 |
28 | function callHandler(handlerName, data, responseCallback) {
29 | if(arguments.length == 2 && typeof data == 'function') {
30 | responseCallback = data;
31 | data = null;
32 | }
33 | _doSend({
34 | handlerName: handlerName,
35 | data: data
36 | }, responseCallback);
37 | }
38 |
39 | function disableJavscriptAlertBoxSafetyTimeout() {
40 | dispatchMessagesWithTimeoutSafety = false;
41 | }
42 |
43 | function _doSend(message, responseCallback) {
44 | if(responseCallback) {
45 | var callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime();
46 | responseCallbacks[callbackId] = responseCallback;
47 | message['callbackId'] = callbackId;
48 | }
49 | sendMessageQueue.push(message);
50 | messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
51 | }
52 |
53 | function _fetchQueue() {
54 | var messageQueueString = JSON.stringify(sendMessageQueue);
55 | sendMessageQueue = [];
56 | messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://'+ QUEUE_RETURN_MESSAGE+ '/' + messageQueueString;
57 | }
58 |
59 | function _dispatchMessageFromObjC(messageJSON) {
60 | if(dispatchMessagesWithTimeoutSafety) {
61 | setTimeout(_doDispatchMessageFromObjC);
62 | } else {
63 | _doDispatchMessageFromObjC();
64 | }
65 |
66 | function _doDispatchMessageFromObjC() {
67 | var message = JSON.parse(messageJSON);
68 | var messageHandler;
69 | var responseCallback;
70 |
71 | if(message.responseId) {
72 | responseCallback = responseCallbacks[message.responseId];
73 | if(!responseCallback) {
74 | return;
75 | }
76 |
77 | try{
78 | responseCallback(JSON.parse(message.responseData));
79 | }catch(e){
80 | responseCallback(message.responseData);
81 | }
82 |
83 | delete responseCallbacks[message.responseId];
84 | } else {
85 | if(message.callbackId) {
86 | var callbackResponseId = message.callbackId;
87 | responseCallback = function(responseData) {
88 | _doSend({
89 | handlerName: message.handlerName,
90 | responseId: callbackResponseId,
91 | responseData: responseData
92 | });
93 | };
94 | }
95 |
96 | var handler = messageHandlers[message.handlerName];
97 | if(!handler) {
98 | console.log("WebViewJavascriptBridge: WARNING: no handler for message from ObjC:", message);
99 | } else {
100 | handler(message.data, responseCallback);
101 | }
102 | }
103 | }
104 | }
105 |
106 | function _handleMessageFromObjC(messageJSON) {
107 | _dispatchMessageFromObjC(messageJSON);
108 | }
109 |
110 |
111 | window.WebViewJavascriptBridge = {
112 | registerHandler: registerHandler,
113 | callHandler: callHandler,
114 | disableJavscriptAlertBoxSafetyTimeout: disableJavscriptAlertBoxSafetyTimeout,
115 | _fetchQueue: _fetchQueue,
116 | _handleMessageFromObjC: _handleMessageFromObjC
117 | };
118 |
119 |
120 | messagingIframe = document.createElement('iframe');
121 | messagingIframe.style.display = 'none';
122 | messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
123 | document.documentElement.appendChild(messagingIframe);
124 |
125 | registerHandler("_disableJavascriptAlertBoxSafetyTimeout", disableJavscriptAlertBoxSafetyTimeout);
126 |
127 | setTimeout(_callWVJBCallbacks, 0);
128 |
129 | function _callWVJBCallbacks() {
130 | var callbacks = window.WVJBCallbacks;
131 | delete window.WVJBCallbacks;
132 | for(var i = 0; i < callbacks.length; i++) {
133 | callbacks[i](window.WebViewJavascriptBridge);
134 | }
135 | }
136 | })();
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/BridgeInterface.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.webviewjavascriptbridge;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 |
6 | import java.util.concurrent.ExecutorService;
7 |
8 | /**
9 | * Title :
10 | * Author : luffyjet
11 | * Date : 2016/12/20
12 | * Project : branch_1009
13 | * Site : http://www.luffyjet.com
14 | */
15 |
16 | public interface BridgeInterface {
17 | /**
18 | * Launch an activity for which you would like a result when it finished. When this activity exits,
19 | * your onActivityResult() method will be called.
20 | *
21 | * @param command The command object
22 | * @param intent The intent to start
23 | * @param requestCode The request code that is passed to callback to identify the activity
24 | */
25 | abstract public void startActivityForResult(RequestHandler command, Intent intent, int requestCode);
26 |
27 | /**
28 | * Set the plugin to be called when a sub-activity exits.
29 | *
30 | * @param plugin The plugin on which onActivityResult is to be called
31 | */
32 | abstract public void setActivityResultCallback(RequestHandler plugin);
33 |
34 | /**
35 | * Get the Android activity.
36 | *
37 | * @return the Activity
38 | */
39 | public abstract Activity getActivity();
40 |
41 |
42 | /**
43 | * Returns a shared thread pool that can be used for background tasks.
44 | */
45 | public ExecutorService getThreadPool();
46 | }
47 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/ConfigXmlParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | Licensed to the Apache Software Foundation (ASF) under one
3 | or more contributor license agreements. See the NOTICE file
4 | distributed with this work for additional information
5 | regarding copyright ownership. The ASF licenses this file
6 | to you under the Apache License, Version 2.0 (the
7 | "License"); you may not use this file except in compliance
8 | with the License. You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing,
13 | software distributed under the License is distributed on an
14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | KIND, either express or implied. See the License for the
16 | specific language governing permissions and limitations
17 | under the License.
18 | */
19 |
20 | package com.luffyjet.webviewjavascriptbridge;
21 |
22 | import android.content.Context;
23 |
24 | import org.xmlpull.v1.XmlPullParser;
25 | import org.xmlpull.v1.XmlPullParserException;
26 |
27 | import java.io.IOException;
28 | import java.util.ArrayList;
29 |
30 | public class ConfigXmlParser {
31 | private ArrayList pluginEntries = new ArrayList();
32 | boolean insideFeature = false;
33 | String service = "", pluginClass = "", paramType = "";
34 | boolean onload = false;
35 |
36 | public ArrayList getHandlerEntries() {
37 | return pluginEntries;
38 | }
39 |
40 | public void parse(Context action) {
41 | // First checking the class namespace for config.xml
42 | int id = action.getResources().getIdentifier("wjbconfig", "xml", action.getClass().getPackage().getName());
43 | if (id == 0) {
44 | // If we couldn't find config.xml there, we'll look in the namespace from AndroidManifest.xml
45 | id = action.getResources().getIdentifier("wjbconfig", "xml", action.getPackageName());
46 | if (id == 0) {
47 | return;
48 | }
49 | }
50 | parse(action.getResources().getXml(id));
51 | }
52 |
53 | public void parse(XmlPullParser xml) {
54 | int eventType = -1;
55 |
56 | while (eventType != XmlPullParser.END_DOCUMENT) {
57 | if (eventType == XmlPullParser.START_TAG) {
58 | handleStartTag(xml);
59 | }
60 | else if (eventType == XmlPullParser.END_TAG)
61 | {
62 | handleEndTag(xml);
63 | }
64 | try {
65 | eventType = xml.next();
66 | } catch (XmlPullParserException e) {
67 | e.printStackTrace();
68 | } catch (IOException e) {
69 | e.printStackTrace();
70 | }
71 | }
72 | }
73 |
74 | public void handleStartTag(XmlPullParser xml) {
75 | String strNode = xml.getName();
76 | if (strNode.equals("feature")) {
77 | //Check for supported feature sets aka. plugins (Accelerometer, Geolocation, etc)
78 | //Set the bit for reading params
79 | insideFeature = true;
80 | service = xml.getAttributeValue(null, "name");
81 | }
82 | else if (insideFeature && strNode.equals("param")) {
83 | paramType = xml.getAttributeValue(null, "name");
84 | if (paramType.equals("service")) // check if it is using the older service param
85 | service = xml.getAttributeValue(null, "value");
86 | else if (paramType.equals("package") || paramType.equals("android-package"))
87 | pluginClass = xml.getAttributeValue(null,"value");
88 | else if (paramType.equals("onload"))
89 | onload = "true".equals(xml.getAttributeValue(null, "value"));
90 | }
91 | }
92 |
93 | public void handleEndTag(XmlPullParser xml) {
94 | String strNode = xml.getName();
95 | if (strNode.equals("feature")) {
96 | pluginEntries.add(new HandlerEntry(service, pluginClass, onload));
97 |
98 | service = "";
99 | pluginClass = "";
100 | insideFeature = false;
101 | onload = false;
102 | }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/HandlerEntry.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.webviewjavascriptbridge;
2 |
3 | /**
4 | * Title :
5 | * Author : luffyjet
6 | * Date : 2016/12/19
7 | * Project : WebViewJavaScriptBridge
8 | * Site : http://www.luffyjet.com
9 | */
10 |
11 | public class HandlerEntry {
12 |
13 | /**
14 | * The name of the service that this handler implements
15 | */
16 | public final String service;
17 |
18 | /**
19 | * The handler class name that implements the service.
20 | */
21 | public final String handlerClass;
22 |
23 | /**
24 | * The pre-instantiated handler to use for this entry.
25 | */
26 | public final RequestHandler handler;
27 |
28 | /**
29 | * Flag that indicates the handler object should be created when PluginManager is initialized.
30 | */
31 | public final boolean onload;
32 |
33 | /**
34 | * Constructs with a handler already instantiated.
35 | */
36 | public HandlerEntry(String service, RequestHandler handler) {
37 | this(service, handler.getClass().getName(), true, handler);
38 | }
39 |
40 | /**
41 | * @param service The name of the service
42 | * @param handlerClass The handler class name
43 | * @param onload Create handler object when HTML page is loaded
44 | */
45 | public HandlerEntry(String service, String handlerClass, boolean onload) {
46 | this(service, handlerClass, onload, null);
47 | }
48 |
49 | private HandlerEntry(String service, String handlerClass, boolean onload, RequestHandler handler) {
50 | this.service = service;
51 | this.handlerClass = handlerClass;
52 | this.onload = onload;
53 | this.handler = handler;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/HandlerManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | Licensed to the Apache Software Foundation (ASF) under one
3 | or more contributor license agreements. See the NOTICE file
4 | distributed with this work for additional information
5 | regarding copyright ownership. The ASF licenses this file
6 | to you under the Apache License, Version 2.0 (the
7 | "License"); you may not use this file except in compliance
8 | with the License. You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing,
13 | software distributed under the License is distributed on an
14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | KIND, either express or implied. See the License for the
16 | specific language governing permissions and limitations
17 | under the License.
18 | */
19 | package com.luffyjet.webviewjavascriptbridge;
20 |
21 | import android.content.Context;
22 | import android.os.Debug;
23 | import android.text.TextUtils;
24 | import android.util.Log;
25 |
26 | import org.json.JSONObject;
27 |
28 | import java.util.Collection;
29 | import java.util.LinkedHashMap;
30 |
31 | /**
32 | *
33 | * Manager Hanlders
34 | *
35 | */
36 | public class HandlerManager {
37 | private static final String TAG = HandlerManager.class.getSimpleName();
38 |
39 | private static final int SLOW_EXEC_WARNING_THRESHOLD = Debug.isDebuggerConnected() ? 60 : 16;
40 |
41 | // List of service entries
42 | private final LinkedHashMap pluginMap = new LinkedHashMap();
43 | private final LinkedHashMap entryMap = new LinkedHashMap();
44 |
45 | private final Context ctx;
46 | protected BridgeInterface mBridgeInterface;
47 | private boolean isInitialized;
48 |
49 | public HandlerManager(Context context, Collection pluginEntries) {
50 | this.ctx = context;
51 | if (context instanceof BridgeInterface) {
52 | mBridgeInterface = (BridgeInterface) context;
53 | }
54 | setPluginEntries(pluginEntries);
55 | }
56 |
57 | public Collection getPluginEntries() {
58 | return entryMap.values();
59 | }
60 |
61 | public void setPluginEntries(Collection pluginEntries) {
62 | if (isInitialized) {
63 | pluginMap.clear();
64 | entryMap.clear();
65 | }
66 | for (HandlerEntry entry : pluginEntries) {
67 | addService(entry);
68 | }
69 | if (isInitialized) {
70 | startupPlugins();
71 | }
72 | }
73 |
74 | /**
75 | * Init when loading a new HTML page into webview.
76 | */
77 | public void init() {
78 | isInitialized = true;
79 | pluginMap.clear();
80 | this.startupPlugins();
81 | }
82 |
83 | /**
84 | * Create plugins objects that have onload set.
85 | */
86 | private void startupPlugins() {
87 | for (HandlerEntry entry : entryMap.values()) {
88 | // Add a null entry to for each non-startup plugin to avoid ConcurrentModificationException
89 | // When iterating plugins.
90 | if (entry.onload) {
91 | getPlugin(entry.service);
92 | } else {
93 | pluginMap.put(entry.service, null);
94 | }
95 | }
96 | }
97 |
98 |
99 | public void exec(final String service, final String action, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
100 | RequestHandler plugin = getPlugin(service);
101 | if (plugin == null) {
102 | Log.i(TAG, "exec() call to unknown plugin: " + service);
103 | // if (null != responseCallback) {
104 | // responseCallback.callback(new JSResult(false).setErrorMessage("no RequestHandler for this request").toJson());
105 | // }
106 | return;
107 | }
108 |
109 | try {
110 | long pluginStartTime = System.currentTimeMillis();
111 |
112 | plugin.handle(!TextUtils.isEmpty(action) ? new JSONObject(action) : new JSONObject(), responseCallback);
113 |
114 | long duration = System.currentTimeMillis() - pluginStartTime;
115 |
116 | if (duration > SLOW_EXEC_WARNING_THRESHOLD) {
117 | Log.w(TAG, "THREAD WARNING: exec() call to " + service + "." + action + " blocked the main thread for " + duration + "ms. Plugin should use CordovaInterface.getThreadPool().");
118 | }
119 |
120 | } catch (Exception e) {
121 | e.printStackTrace();
122 | }
123 | }
124 |
125 | /**
126 | * Get the plugin object that implements the service.
127 | * If the plugin object does not already exist, then create it.
128 | * If the service doesn't exist, then return null.
129 | *
130 | * @param service The name of the service.
131 | * @return CordovaPlugin or null
132 | */
133 | public RequestHandler getPlugin(String service) {
134 | RequestHandler ret = pluginMap.get(service);
135 | if (ret == null) {
136 | HandlerEntry pe = entryMap.get(service);
137 | if (pe == null) {
138 | return null;
139 | }
140 | if (pe.handler != null) {
141 | ret = pe.handler;
142 | } else {
143 | ret = instantiatePlugin(pe.handlerClass);
144 | }
145 | ret.privateInitialize(service, ctx, mBridgeInterface);
146 | pluginMap.put(service, ret);
147 | }
148 | return ret;
149 | }
150 |
151 | /**
152 | * Add a plugin class that implements a service to the service entry table.
153 | * This does not create the plugin object instance.
154 | *
155 | * @param service The service name
156 | * @param className The plugin class name
157 | */
158 | public void addService(String service, String className) {
159 | HandlerEntry entry = new HandlerEntry(service, className, false);
160 | this.addService(entry);
161 | }
162 |
163 | /**
164 | * Add a plugin class that implements a service to the service entry table.
165 | * This does not create the plugin object instance.
166 | *
167 | * @param entry The plugin entry
168 | */
169 | public void addService(HandlerEntry entry) {
170 | this.entryMap.put(entry.service, entry);
171 | if (entry.handler != null) {
172 | entry.handler.privateInitialize(entry.service, ctx, mBridgeInterface);
173 | pluginMap.put(entry.service, entry.handler);
174 | }
175 | }
176 |
177 |
178 | /**
179 | * Create a plugin based on class name.
180 | */
181 | private RequestHandler instantiatePlugin(String className) {
182 | RequestHandler ret = null;
183 | try {
184 | Class> c = null;
185 | if ((className != null) && !("".equals(className))) {
186 | c = Class.forName(className);
187 | }
188 | if (c != null & RequestHandler.class.isAssignableFrom(c)) {
189 | ret = (RequestHandler) c.newInstance();
190 | }
191 | } catch (Exception e) {
192 | e.printStackTrace();
193 | System.out.println("Error adding handler " + className + ".");
194 | }
195 | return ret;
196 | }
197 | }
198 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/JSResult.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.webviewjavascriptbridge;
2 |
3 | import org.json.JSONException;
4 | import org.json.JSONObject;
5 |
6 | /**
7 | * Title :
8 | * Author : luffyjet
9 | * Date : 2017/4/27
10 | * Project : WebViewJavaScriptBridge
11 | * Site : http://www.luffyjet.com
12 | */
13 |
14 | public class JSResult {
15 | public boolean status;
16 | public String resultStr;
17 | public String errorMessage;
18 |
19 | public JSResult() {
20 | }
21 |
22 | public JSResult(boolean result) {
23 | status = result;
24 | }
25 |
26 | public JSResult(String result) {
27 | resultStr = result;
28 | status = true;
29 | }
30 |
31 | public JSResult setErrorMessage(String message) {
32 | errorMessage = message;
33 | return this;
34 | }
35 |
36 |
37 | public String toJson() {
38 | JSONObject jsonObject = new JSONObject();
39 | try {
40 | jsonObject.put("status", status);
41 | jsonObject.put("resultStr", resultStr);
42 | jsonObject.put("errorMessage", errorMessage);
43 | } catch (JSONException e) {
44 | e.printStackTrace();
45 | }
46 | return jsonObject.toString();
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/RequestHandler.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.webviewjavascriptbridge;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.util.Log;
6 |
7 | /**
8 | * Title :
9 | * Author : luffyjet
10 | * Date : 2016/12/16
11 | * Project : WebViewJavaScriptBridge
12 | * Site : http://www.luffyjet.com
13 | */
14 |
15 | public abstract class RequestHandler implements WebViewJavaScriptBridgeBase.WVJBHandler {
16 | protected BridgeInterface mBridgeInterface;
17 | protected Context mContext;
18 | private String service;
19 |
20 | public RequestHandler() {
21 | }
22 |
23 | public void log(String msg) {
24 | if (WebViewJavaScriptBridgeBase.logging) {
25 | Log.d("RequestHandler", msg);
26 | }
27 | }
28 |
29 |
30 | public void log(String tag, String msg) {
31 | if (WebViewJavaScriptBridgeBase.logging) {
32 | Log.d(tag, msg);
33 | }
34 | }
35 |
36 | protected String getHandlerName() {
37 | return service;
38 | }
39 |
40 | public void onActivityResult(int requestCode, int resultCode, Intent data){
41 |
42 | }
43 |
44 | public void onPayResult(String result, String message){
45 |
46 | }
47 |
48 | void privateInitialize(String service, Context ctx , BridgeInterface bridgeInterface) {
49 | this.service = service;
50 | mContext = ctx;
51 | mBridgeInterface = bridgeInterface;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/Utils.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.webviewjavascriptbridge;
2 |
3 | import android.content.Context;
4 |
5 | import java.io.BufferedReader;
6 | import java.io.IOException;
7 | import java.io.InputStream;
8 | import java.io.InputStreamReader;
9 |
10 | /**
11 | * Title :
12 | * Author : luffyjet
13 | * Date : 2016/12/15
14 | * Project : WebViewJavaScriptBridge
15 | * Site : http://www.luffyjet.com
16 | */
17 |
18 | public class Utils {
19 |
20 | static String getLocalJs(Context context, String path) {
21 | String js = assets2Str(context, path);
22 | return "javascript:" + js;
23 | }
24 |
25 |
26 | private static String assets2Str(Context c, String urlStr) {
27 | InputStream in = null;
28 | try {
29 | in = c.getAssets().open(urlStr);
30 | BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
31 | String line = null;
32 | StringBuilder sb = new StringBuilder();
33 | do {
34 | line = bufferedReader.readLine();
35 | sb.append(line);
36 | } while (line != null);
37 |
38 | bufferedReader.close();
39 | in.close();
40 |
41 | return sb.toString();
42 | } catch (Exception e) {
43 | e.printStackTrace();
44 | } finally {
45 | if (in != null) {
46 | try {
47 | in.close();
48 | } catch (IOException e) {
49 | }
50 | }
51 | }
52 | return null;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/WebViewJavaScriptBridge.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.webviewjavascriptbridge;
2 |
3 | import android.annotation.TargetApi;
4 | import android.content.Context;
5 | import android.graphics.Bitmap;
6 | import android.net.Uri;
7 | import android.os.Build;
8 | import android.os.Looper;
9 | import android.text.TextUtils;
10 | import android.util.Log;
11 | import android.webkit.WebResourceRequest;
12 | import android.webkit.WebResourceResponse;
13 | import android.webkit.WebView;
14 | import android.webkit.WebViewClient;
15 |
16 | import java.io.File;
17 | import java.io.FileInputStream;
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.io.UnsupportedEncodingException;
21 | import java.lang.ref.WeakReference;
22 | import java.net.URLDecoder;
23 |
24 |
25 | /**
26 | * Title :
27 | * Author : luffyjet
28 | * Date : 2016/12/14
29 | * Project : WebViewJavaScriptBridge
30 | * Site : http://www.luffyjet.com
31 | */
32 |
33 | public class WebViewJavaScriptBridge extends WebViewClient implements WebViewJavaScriptBridgeBase.WebViewJavascriptBridgeBaseDelegate {
34 |
35 | private static final String TAG = WebViewJavaScriptBridge.class.getSimpleName();
36 | private WeakReference _webView;
37 | private WeakReference _webViewDelegate;
38 | private WebViewJavaScriptBridgeBase _base;
39 | public static final String LOCAL_FILE_SCHEMA = "wjbfile://";
40 |
41 | private WebViewJavaScriptBridge() {
42 |
43 | }
44 |
45 |
46 | public static void enableLogging() {
47 | WebViewJavaScriptBridgeBase.enableLogging();
48 | }
49 |
50 |
51 | public static WebViewJavaScriptBridge bridgeForWebView(Context activity, WebView webView) {
52 | WebViewJavaScriptBridge bridge = new WebViewJavaScriptBridge();
53 | bridge.platformSpecificSetup(activity, webView);
54 | return bridge;
55 | }
56 |
57 | public void setWebViewDelegate(WebViewClient webViewDelegate) {
58 | _webViewDelegate = new WeakReference<>(webViewDelegate);
59 | }
60 |
61 | public void send(Object data) {
62 | send(data, null);
63 | }
64 |
65 | public void send(Object data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
66 | _base.sendData(data, responseCallback, null);
67 | }
68 |
69 | public void callHandler(String handlerName) {
70 | callHandler(handlerName, null, null);
71 | }
72 |
73 | public void callHandler(String handlerName, Object data) {
74 | callHandler(handlerName, data, null);
75 | }
76 |
77 | public void callHandler(String handlerName, Object data, WebViewJavaScriptBridgeBase.WVJBResponseCallback responseCallback) {
78 | _base.sendData(data, responseCallback, handlerName);
79 | }
80 |
81 | public void registerHandler(RequestHandler handler) {
82 | registerHandler(handler.getHandlerName(), handler);
83 | }
84 |
85 | public void registerHandler(String handlerName, WebViewJavaScriptBridgeBase.WVJBHandler handler) {
86 | _base.messageHandlers.put(handlerName, handler);
87 | }
88 |
89 | public void disableJavscriptAlertBoxSafetyTimeout() {
90 | _base.disableJavscriptAlertBoxSafetyTimeout();
91 | }
92 |
93 |
94 | @Override
95 | public void evaluateJavascript(String javascriptCommand) {
96 | if (null != _webView && null != _webView.get()) {
97 | _webView.get().loadUrl(javascriptCommand);
98 | }
99 | }
100 |
101 | private void platformSpecificSetup(Context activity, WebView webView) {
102 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
103 | WebView.setWebContentsDebuggingEnabled(true);
104 | }
105 |
106 | webView.setWebViewClient(this);
107 |
108 | ConfigXmlParser parser = new ConfigXmlParser();
109 | parser.parse(activity);
110 |
111 | _webView = new WeakReference<>(webView);
112 | _base = new WebViewJavaScriptBridgeBase();
113 | _base.init(activity, parser.getHandlerEntries());
114 | _base.setDelegate(this);
115 | }
116 |
117 |
118 | @Override
119 | public void onPageFinished(WebView view, String url) {
120 | super.onPageFinished(view, url);
121 | if (null != _webViewDelegate && null != _webViewDelegate.get())
122 | _webViewDelegate.get().onPageFinished(view, url);
123 | }
124 |
125 |
126 | @Override
127 | public void onReceivedError(WebView webView, int i, String s, String s1) {
128 | super.onReceivedError(webView, i, s, s1);
129 | if (null != _webViewDelegate && null != _webViewDelegate.get())
130 | _webViewDelegate.get().onReceivedError(webView, i, s, s1);
131 | }
132 |
133 |
134 | @Override
135 | public void onPageStarted(WebView view, String url, Bitmap favicon) {
136 | super.onPageStarted(view, url, favicon);
137 | if (null != _webViewDelegate && null != _webViewDelegate.get())
138 | _webViewDelegate.get().onPageStarted(view, url, favicon);
139 | }
140 |
141 |
142 | @Override
143 | public boolean shouldOverrideUrlLoading(WebView view, String url) {
144 | Uri uri = Uri.parse(url);
145 | if (_base.isCorrectProcotocolScheme(uri)) {
146 | if (_base.isBridgeLoadedURL(uri)) {
147 | _base.injectJavascriptFile(view.getContext());
148 | } else if (_base.isQueueMessageURL(uri)) {
149 | if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
150 | evaluateJavascript(_base.webViewJavascriptFetchQueyCommand());
151 | _base.responseCallbacks.put(WebViewJavaScriptBridgeBase.QUEUE_HAS_MESSAGE, new WebViewJavaScriptBridgeBase.WVJBResponseCallback() {
152 | @Override
153 | public void callback(String responseData) {
154 | _base.flushMessageQueue(responseData);
155 | }
156 | });
157 | }
158 | } else if (_base.isReturnMessageURL(uri)) {
159 | String data = uri.toString().replace(WebViewJavaScriptBridgeBase.QUEUE_FETCH_MESSAGE, "");
160 | WebViewJavaScriptBridgeBase.WVJBResponseCallback callback = _base.responseCallbacks.get(WebViewJavaScriptBridgeBase.QUEUE_HAS_MESSAGE);
161 | if (null != callback) {
162 | callback.callback(data);
163 | _base.responseCallbacks.remove(WebViewJavaScriptBridgeBase.QUEUE_HAS_MESSAGE);
164 | }
165 | } else {
166 | _base.logUnkownMessage(uri);
167 | }
168 | return true;
169 | } else {
170 | if (null != _webViewDelegate && null != _webViewDelegate.get()) {
171 | WebViewClient webViewClient = _webViewDelegate.get();
172 | return webViewClient.shouldOverrideUrlLoading(view, url);
173 | }
174 | }
175 | return super.shouldOverrideUrlLoading(view, url);
176 | }
177 |
178 | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
179 | @Override
180 | public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
181 | String url = null != webResourceRequest.getUrl() ? webResourceRequest.getUrl().toString() : null;
182 | if (!TextUtils.isEmpty(url) && url.startsWith(LOCAL_FILE_SCHEMA)) {
183 | return getLocalResource(url);
184 | }
185 |
186 | if (null != _webViewDelegate && null != _webViewDelegate.get()) {
187 | return _webViewDelegate.get().shouldInterceptRequest(webView, webResourceRequest);
188 | }
189 | return super.shouldInterceptRequest(webView, webResourceRequest);
190 | }
191 |
192 |
193 | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
194 | @Override
195 | public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
196 | if (!TextUtils.isEmpty(url) && url.startsWith(LOCAL_FILE_SCHEMA)) {
197 | return getLocalResource(url);
198 | }
199 |
200 | if (null != _webViewDelegate && null != _webViewDelegate.get()) {
201 | return _webViewDelegate.get().shouldInterceptRequest(view, url);
202 | }
203 | return super.shouldInterceptRequest(view, url);
204 | }
205 |
206 |
207 | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
208 | private WebResourceResponse getLocalResource(String url) {
209 | WebResourceResponse response = null;
210 | try {
211 | url = URLDecoder.decode(url, "UTF-8");
212 | } catch (UnsupportedEncodingException e) {
213 | e.printStackTrace();
214 | }
215 |
216 | File file = new File(url.replace(LOCAL_FILE_SCHEMA, ""));
217 | if (file.exists()) {
218 | try {
219 | InputStream localCopy = new FileInputStream(file);
220 | String mimeType = getMimeType(url);
221 | response = new WebResourceResponse(mimeType, "UTF-8", localCopy);
222 | } catch (IOException e) {
223 | e.printStackTrace();
224 | }
225 | } else {
226 | Log.e("shouldInterceptRequest", "file is not exists!");
227 | }
228 | return response;
229 | }
230 |
231 | private String getMimeType(String url) {
232 | if (url.contains(".")) {
233 | int index = url.lastIndexOf(".");
234 | if (index > -1) {
235 | int paramIndex = url.indexOf("?");
236 | String type = url.substring(index + 1, paramIndex == -1 ? url.length() : paramIndex);
237 | switch (type) {
238 | case "js":
239 | return "text/javascript";
240 | case "css":
241 | return "text/css";
242 | case "html":
243 | return "text/html";
244 | case "png":
245 | return "image/png";
246 | case "jpg":
247 | return "image/jpg";
248 | case "gif":
249 | return "image/gif";
250 | }
251 | }
252 | }
253 | return "text/plain";
254 | }
255 |
256 | }
257 |
--------------------------------------------------------------------------------
/library/src/main/java/com/luffyjet/webviewjavascriptbridge/WebViewJavaScriptBridgeBase.java:
--------------------------------------------------------------------------------
1 | package com.luffyjet.webviewjavascriptbridge;
2 |
3 | import android.content.Context;
4 | import android.net.Uri;
5 | import android.os.Looper;
6 | import android.text.TextUtils;
7 | import android.util.Log;
8 |
9 | import org.json.JSONArray;
10 | import org.json.JSONException;
11 | import org.json.JSONObject;
12 |
13 | import java.util.ArrayList;
14 | import java.util.HashMap;
15 | import java.util.List;
16 |
17 |
18 | /**
19 | * Title :
20 | * Author : luffyjet
21 | * Date : 2016/12/13
22 | * Project : WebViewJavaScriptBridge
23 | * Site : http://www.luffyjet.com
24 | */
25 |
26 | public class WebViewJavaScriptBridgeBase {
27 | private static final String TAG = WebViewJavaScriptBridgeBase.class.getSimpleName();
28 | private static final String PROTOCOL_SCHEME = "wvjbscheme";
29 | static final String QUEUE_HAS_MESSAGE = "__WVJB_QUEUE_MESSAGE__";
30 | private static final String QUEUE_RETURN_MESSAGE = "__WVJB_RETURN_MESSAGE__";
31 | private static final String BRIDGE_LOADED = "__BRIDGE_LOADED__";
32 | static final String QUEUE_FETCH_MESSAGE = PROTOCOL_SCHEME + "://" + QUEUE_RETURN_MESSAGE + "/";
33 |
34 | static boolean logging = false;
35 |
36 | interface WebViewJavascriptBridgeBaseDelegate {
37 | void evaluateJavascript(String javascriptCommand);
38 | }
39 |
40 | public interface WVJBResponseCallback {
41 | void callback(String responseData);
42 | }
43 |
44 |
45 | public interface WVJBHandler {
46 | void handle(JSONObject data, WVJBResponseCallback responseCallback);
47 | }
48 |
49 | private WebViewJavascriptBridgeBaseDelegate delegate;
50 | private ArrayList> startupMessageQueue;
51 | HashMap responseCallbacks;
52 | HashMap messageHandlers;
53 | private HandlerManager mHandlerManager;
54 | private long _uniqueId;
55 |
56 |
57 | static void enableLogging() {
58 | logging = true;
59 | }
60 |
61 |
62 | WebViewJavaScriptBridgeBase init(Context context, List pluginEntries) {
63 | this.messageHandlers = new HashMap<>();
64 | this.startupMessageQueue = new ArrayList<>();
65 | this.responseCallbacks = new HashMap<>();
66 |
67 | mHandlerManager = new HandlerManager(context, pluginEntries);
68 | mHandlerManager.init();
69 |
70 | _uniqueId = 0;
71 | return this;
72 | }
73 |
74 |
75 | void sendData(Object data, WVJBResponseCallback responseCallback, String handlerName) {
76 | HashMap message = new HashMap<>();
77 |
78 | if (null != data) {
79 | message.put("data", data);
80 | }
81 |
82 | if (null != responseCallback) {
83 | String callbackId = String.format("objc_cb_%s", ++_uniqueId);
84 | responseCallbacks.put(callbackId, responseCallback);
85 | message.put("callbackId", callbackId);
86 | }
87 |
88 | if (!TextUtils.isEmpty(handlerName)) {
89 | message.put("handlerName", handlerName);
90 | }
91 |
92 | _queueMessage(message);
93 | }
94 |
95 | void flushMessageQueue(String messageQueueString) {
96 | if (TextUtils.isEmpty(messageQueueString)) {
97 | Log.e(TAG, "WebViewJavascriptBridge: WARNING: ObjC got nil while fetching the message queue JSON from webview. This can happen if the WebViewJavascriptBridge JS is not currently present in the webview, e.g if the webview just loaded a new page.");
98 | return;
99 | }
100 |
101 | JSONArray messages = _deserializeMessageJSON(messageQueueString);
102 |
103 | if (messages != null) {
104 | for (int i = 0; i < messages.length(); i++) {
105 | try {
106 | JSONObject message = messages.optJSONObject(i);
107 |
108 | log("flushMessageQueue", message.toString());
109 |
110 | String responseId = null;
111 |
112 | responseId = message.optString("responseId");
113 |
114 | if (!TextUtils.isEmpty(responseId)) {
115 | WVJBResponseCallback responseCallback = responseCallbacks.get(responseId);
116 | responseCallback.callback(message.optString("responseData"));
117 | responseCallbacks.remove(responseId);
118 | } else {
119 | WVJBResponseCallback responseCallback = null;
120 | final String callbackId = message.optString("callbackId");
121 | if (!TextUtils.isEmpty(callbackId)) {
122 | responseCallback = new WVJBResponseCallback() {
123 | @Override
124 | public void callback(String responseData) {
125 | HashMap msg = new HashMap<>();
126 | msg.put("responseId", callbackId);
127 | msg.put("responseData", responseData);
128 | _queueMessage(msg);
129 | }
130 | };
131 | } else {
132 | responseCallback = new WVJBResponseCallback() {
133 | @Override
134 | public void callback(String responseData) {
135 |
136 | }
137 | };
138 | }
139 |
140 | mHandlerManager.exec(message.optString("handlerName"), message.optString("data"), responseCallback);
141 |
142 |
143 | WVJBHandler handler = messageHandlers.get(message.optString("handlerName"));
144 |
145 | if (null == handler) {
146 | Log.e(TAG, String.format("WVJBNoHandlerException, No handler for message from JS: %s", message));
147 | continue;
148 | }
149 |
150 | String action = message.optString("data");
151 | handler.handle(!TextUtils.isEmpty(action) ? new JSONObject(action) : new JSONObject(), responseCallback);
152 | }
153 | } catch (Exception e) {
154 | e.printStackTrace();
155 | }
156 | }
157 | }
158 | }
159 |
160 |
161 | void injectJavascriptFile(Context context) {
162 | String js = Utils.getLocalJs(context, "webviewjsbridge.js");
163 | _evaluateJavascript(js);
164 |
165 | if (null != startupMessageQueue) {
166 | ArrayList> queue = new ArrayList<>();
167 | queue.addAll(startupMessageQueue);
168 | startupMessageQueue = null;
169 | for (HashMap queuedMessage : queue) {
170 | _dispatchMessage(queuedMessage);
171 | }
172 | }
173 | }
174 |
175 |
176 | boolean isCorrectProcotocolScheme(Uri url) {
177 | return !(null == url || null == url.getScheme()) && url.getScheme().equals(PROTOCOL_SCHEME);
178 | }
179 |
180 | boolean isQueueMessageURL(Uri url) {
181 | return !(null == url || null == url.getHost()) && url.getHost().equals(QUEUE_HAS_MESSAGE);
182 | }
183 |
184 | boolean isReturnMessageURL(Uri url) {
185 | return !(null == url || null == url.getHost()) && url.getHost().equals(QUEUE_RETURN_MESSAGE);
186 | }
187 |
188 | boolean isBridgeLoadedURL(Uri url) {
189 | return !(null == url || null == url.getScheme() || null == url.getHost()) && url.getScheme().equals(PROTOCOL_SCHEME) && url.getHost().equals(BRIDGE_LOADED);
190 | }
191 |
192 | void logUnkownMessage(Uri url) {
193 | Log.i(TAG, String.format("WebViewJavascriptBridge: WARNING: Received unknown WebViewJavascriptBridge command %s://%s", PROTOCOL_SCHEME, url.getPath()));
194 | }
195 |
196 | public String webViewJavascriptCheckCommand() {
197 | return "javascript:typeof WebViewJavascriptBridge == \'object\';";
198 | }
199 |
200 | String webViewJavascriptFetchQueyCommand() {
201 | return "javascript:WebViewJavascriptBridge._fetchQueue();";
202 | }
203 |
204 | void disableJavscriptAlertBoxSafetyTimeout() {
205 | sendData(null, null, "_disableJavascriptAlertBoxSafetyTimeout");
206 | }
207 |
208 |
209 | private void _evaluateJavascript(String javascriptCommand) {
210 | delegate.evaluateJavascript(javascriptCommand);
211 | }
212 |
213 |
214 | private void _queueMessage(HashMap message) {
215 | if (null != startupMessageQueue) {
216 | startupMessageQueue.add(message);
217 | } else {
218 | _dispatchMessage(message);
219 | }
220 | }
221 |
222 |
223 | private void _dispatchMessage(HashMap message) {
224 | String messageJSON = _serializeMessage(message);
225 |
226 |
227 | messageJSON = messageJSON.replaceAll("(\\\\)([^utrn])", "\\\\\\\\$1$2");
228 | messageJSON = messageJSON.replaceAll("(?<=[^\\\\])(\")", "\\\\\"");
229 |
230 | log("_dispatchMessage", messageJSON);
231 |
232 | final String javascriptCommand = String.format("javascript:WebViewJavascriptBridge._handleMessageFromObjC('%s');", messageJSON);
233 |
234 | if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
235 | this._evaluateJavascript(javascriptCommand);
236 | }
237 | }
238 |
239 | private String _serializeMessage(HashMap message) {
240 | JSONObject jsonObject = new JSONObject();
241 | try {
242 | jsonObject.put("callbackId", message.get("callbackId"));
243 | jsonObject.put("data", message.get("data"));
244 | jsonObject.put("handlerName", message.get("handlerName"));
245 | jsonObject.put("responseData", message.get("responseData"));
246 | jsonObject.put("responseId", message.get("responseId"));
247 | return jsonObject.toString();
248 | } catch (JSONException e) {
249 | e.printStackTrace();
250 | }
251 | return null;
252 | }
253 |
254 |
255 | private JSONArray _deserializeMessageJSON(String messageJSON) {
256 | log("decode", messageJSON);
257 | try {
258 | return new JSONArray(messageJSON);
259 | } catch (JSONException e) {
260 | e.printStackTrace();
261 | }
262 |
263 | return null;
264 | }
265 |
266 |
267 | List getApiList() {
268 | return new ArrayList(messageHandlers.keySet());
269 | }
270 |
271 |
272 | void setDelegate(WebViewJavascriptBridgeBaseDelegate delegate) {
273 | this.delegate = delegate;
274 | }
275 |
276 | private void log(String action, String json) {
277 | if (!logging) {
278 | return;
279 | }
280 | Log.i(TAG, String.format("WVJB %s: %s", action, json));
281 | }
282 | }
283 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------