├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── cookies.md ├── gradle.properties ├── jsbridge.md ├── sample.jpeg ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── index.html │ ├── java │ └── com │ │ └── joey │ │ └── xwebassistant │ │ └── sample │ │ ├── JavaMethod │ │ ├── JSAsyncFunc.java │ │ ├── JSToast.java │ │ ├── JSToastAuthorized.java │ │ ├── JSToastPrivate.java │ │ └── JSToastPublic.java │ │ └── SampleActivity.java │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ └── activity_sample.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── settings.gradle ├── todo.md ├── use.md └── xwebview ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src └── main ├── AndroidManifest.xml ├── assets └── XWebViewJsBridgeCore.js ├── java └── com │ └── joey │ └── xwebview │ ├── XLoadUrl.java │ ├── XWebChromeClient.java │ ├── XWebView.java │ ├── XWebViewClient.java │ ├── cookie │ └── XWebCookies.java │ ├── exception │ └── JSBridgeException.java │ ├── jsbridge │ ├── JSBridgeCore.java │ ├── JSBridgeRegister.java │ └── method │ │ ├── DefaultAuthorizedChecker.java │ │ ├── IAuthorizedChecker.java │ │ ├── JSMessage.java │ │ └── XJavaMethod.java │ ├── log │ └── XWebLog.java │ └── ui │ ├── IWebProgress.java │ ├── IWebTitle.java │ └── XWebProgressBar.java └── res └── values └── strings.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | .idea/ 4 | gradle/ 5 | gradlew 6 | gradlew.bat 7 | /local.properties 8 | /.idea/libraries 9 | /.idea/modules.xml 10 | /.idea/workspace.xml 11 | .DS_Store 12 | /build 13 | /captures 14 | .externalNativeBuild 15 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 | # XWebViewAssistant 文档 2 | 3 | ### 概述 4 | 5 | XWebViewAssistant 提供给Android开发者更简单的WebView开发方式,基于Android原生`WebView`,轻量封装相关操作 6 | 7 | - 链式调用,初始化`WebView` 更简洁 8 | - 无`Activity`或者`Fragment` 基类,不需要继承,在任何页面都可以直接使用 9 | - 自动绑定生命周期,无需手动操作,避免内存泄露 10 | - 支持`JSBridge` ,内部实现为`@JavascriptInterface` ,提供权限校验,前端回调管理,支持同步和异步回调 11 | - 支持 Cookie 同步 12 | 13 | ### 依赖 14 | 15 | 在根目录build.gradle下添加代码 16 | 17 | ```groovy 18 | allprojects { 19 | repositories { 20 | ... 21 | maven { url 'https://jitpack.io' } 22 | } 23 | } 24 | ``` 25 | 26 | 在项目build.gradle 27 | 28 | `latest-version` 请在release-note中查看 29 | 30 | ```java 31 | dependencies { 32 | implementation 'com.github.JoeSteven:XWebViewAssistant:latest-version' 33 | } 34 | ``` 35 | 36 | ### 使用文档 37 | 38 | - [基本用法](./use.md) 39 | - [Js Bridge](./jsbridge.md) 40 | - [Cookies](./cookies.md) 41 | 42 | [todo](./todo.md) 43 | 44 | ### 示例 45 | 46 | - 可以通过输入框输入url进行加载 47 | 48 | 49 | - add whitelist 和 authorize 这两个按钮分别可以将当前网站加入到白名单或者方法授权 50 | 51 | 52 | - function: 后面有三个注册的Java方法,分别对应三种不同的权限,public都可以调用,private需要加入白名单可调用, authorized需要白名单或者授权可以调用。 53 | 54 | 55 | - params:后面为三个方法的参数,json格式 56 | - 最底部输入框为Java调用 js的sample 57 | 58 | **该sample的前端调试页面放在asset目录中,你也可以在接入该库的时候使用这个页面进行本地调试,该页面由猴哥-[Jaeger](https://github.com/laobie) 友情赞助** 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | jcenter() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.1.3' 11 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' 12 | 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 | google() 21 | jcenter() 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | -------------------------------------------------------------------------------- /cookies.md: -------------------------------------------------------------------------------- 1 | # XWebCookies 2 | 3 | 该类提供了 WebView Cookie 的相关操作 4 | 5 | ### 1.初始化 6 | 7 | 使用之前需要先调用初始化代码,只需要调用一次 8 | 9 | ```java 10 | XWebCookies.init(context); 11 | ``` 12 | 13 | ### 2.同步 Cookie 14 | 15 | ```java 16 | // 同步cookie在5.0以上会阻塞线程, 17 | XWebCookies.syncCookie(url, cookie); 18 | XWebCookies.syncCookies(url, cookies); 19 | ``` 20 | 21 | ### 3.获取Cookie 22 | 23 | ```java 24 | XWebCookies.getCookie(url); 25 | ``` 26 | 27 | ### 4.清除cookie 28 | 29 | ```Java 30 | XWebCookies.removeAllCookies(callback); 31 | XWebCookies.removeSessionCookies(callback); 32 | XWebCookies.removeExpiredCookies();// WebView会自动移除过期Cookies 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | -------------------------------------------------------------------------------- /jsbridge.md: -------------------------------------------------------------------------------- 1 | # JsBridge 模块 2 | 3 | **注意:本库底层实现为 @JavascriptInterface 的方式因此只支持到minsdk-18,截止到今天(2018.9.5)minsdk-18 已覆盖90%手机。这种方式相比拦截URL的方式效率上高得多,耗时更低** 4 | 本库采用注册的方式来给前端页面提供 Java 方法,尽量实现每个方法逻辑单一,可复用,便于权限管理提供安全性 5 | 6 | ### 客户端文档 7 | 8 | #### 1.实现 Java 方法 9 | 10 | 提供给 JS 调用的方法需要继承 `XJavaMethod` ,实现两个方法,`call` 和`permission`。 11 | 12 | 在 `call` 中执行业务代码 13 | 14 | - 支持以抛异常的方式来回调前端 15 | - 同步回调,直接返回 `calbackParams` ,将回调所需要的数据放在该 Json 对象中 16 | - return null ,不回调,**如果前端页面注册了回调函数,请务必回调,避免前端页内存泄露** 17 | - 异步回调,在同步代码中return null,然后在异步代码块中调用`callback` 或者`callError` 来分别回调 18 | 19 | ```java 20 | public class JSToastPublic extends XJavaMethod{ 21 | 22 | @Override 23 | public JSONObject call(JSMessage message, JSONObject callbackParams) throws Exception{ 24 | if (TextUtils.isEmpty(message.params.optString("message"))) 25 | throw new Exception("no message found from js"); 26 | 27 | Toast.makeText(context, 28 | message.params.optString("message"), 29 | Toast.LENGTH_SHORT).show(); 30 | 31 | // 同步回调 32 | return callbackParams.put("message", "invoke JSToastPublic success"); 33 | } 34 | 35 | @Override 36 | public Permission permission() { 37 | return Permission.PUBLIC; 38 | } 39 | } 40 | ``` 41 | 42 | - 异步回调 43 | 44 | ```java 45 | public JSONObject call(JSMessage message, JSONObject callbackParams) throws Exception{ 46 | //异步代码中回调 47 | ...//success 48 | callback(message.callbackID, callbackParams.put("message", "success")); 49 | //error 50 | callError(message.callbackID, exception.toString()); 51 | ... 52 | // 必须返回 null, 否则会立即回调 53 | return null; 54 | } 55 | ``` 56 | 57 | - JSMessage 58 | 59 | ```JAVA 60 | public class JSMessage { 61 | public JSMessage() {} 62 | 63 | public String hostUrl;// 当前调用该方法的页面url 64 | public String callbackID;// 回调id,id为"-1"则说明无需回调 65 | public String javaMethod;// 调用的 Java 名称(注册时的名称,并不是真实的函数名) 66 | public JSONObject params;// 参数 67 | } 68 | ``` 69 | 70 | #### 2.权限管理 71 | 72 | 每一个注册的 Java 方法都必须指定调用权限 73 | 74 | ```java 75 | public enum Permission{ 76 | PUBLIC,// 公开方法,所以的网页只要知道该应用的js协议都可以调用 77 | 78 | AUTHORIZED,// 授权方法,只有白名单或者被授权过的网页才可以调用该方法,授权判断由业务层自己实现 79 | 80 | PRIVATE // 私有方法,只有该在该应用中注册了域名白名单的网页可以调用 81 | } 82 | 83 | // 检查该网页是否有该方法的授权接口,默认实现为永远返回false 84 | //例如:应用启动的时候从服务端获取一个对应方法的授权网页列表,调用的时候判断该网页是否有授权 85 | public interface IAuthorizedChecker { 86 | boolean isAuthorized(String javaFunc, String url); 87 | } 88 | 89 | // 设置授权检查接口,该方法必须在setJSBridgeUrlEnabled或者setJSBridgePromptEnabled之后调用 90 | xWeb.setJSBridgeAuthorizedChecker(checker); 91 | ``` 92 | 93 | #### 3.构造 `JSBridgeRegister`, 注册 Java 方法 94 | 95 | ```java 96 | JSBridgeRegister register = JSBridgeRegister.create() 97 | .register("toast", JSToast.class)// js 约定的方法名及真实方法 98 | .register("login", JSLogin.class) 99 | .register("user_info", JSUserInfo.class) 100 | .whiteList("api.xwebview.com")// 设置域名白名单,支持两种方式,域名白名单,或者是正则匹配 101 | .whiteListPattern(Pattern.compile("file:///android_asset.*")); 102 | ``` 103 | 104 | #### 4.`IMethodInitializer` 方法初始化器 105 | 106 | 如果注册的 Java 方法依赖外界注入参数,可以通过设置方法初始化接口,在创建该方法实例后注入参数等 107 | 108 | ```java 109 | register.setMethodInitializer((func, method) -> { 110 | if (method instanceof JSToast) 111 | ((JSToast) method).setContext(SampleActivity.this); 112 | }); 113 | ``` 114 | 115 | #### 5.开启`JSBridge` 116 | 117 | ```java 118 | xWeb.setJSBridgeUrlEnabled(register) 119 | ``` 120 | 121 | ### 前端文档 122 | 123 | 实现 JsBridge 的文件为 XWebViewJsBridgeCore.js,在本仓库`xwebview/src/main/assets/XWebViewJsBridgeCore.js` 124 | 125 | ```javascript 126 | // 调用java 方法 127 | // func - 注册的 java 方法名,string 128 | // params - 参数,JSON 129 | // callback - 回调, function 可选 130 | window.invokeJavaFunc(func, params, callback) 131 | 132 | // 回调函数,接收参数为JSON 133 | function callback(data){ 134 | ... 135 | } 136 | 137 | // 回调数据格式, 138 | { 139 | "status": 0, // 0 - 成功,1-失败 140 | "message": "success", // 状态信息,例如失败后的异常信息 141 | "params": { // 数据 142 | "user": "xxx", 143 | "age": 20 144 | } 145 | } 146 | ``` -------------------------------------------------------------------------------- /sample.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JoeSteven/XWebViewAssistant/74612e57e35ad06c27521dfe08b5d019d2252a65/sample.jpeg -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | 4 | android { 5 | compileSdkVersion 27 6 | defaultConfig { 7 | applicationId "com.joey.xwebassistant.sample" 8 | minSdkVersion 18 9 | targetSdkVersion 27 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | 21 | compileOptions { 22 | targetCompatibility 1.8 23 | sourceCompatibility 1.8 24 | } 25 | } 26 | 27 | group = 'com.github.JoeSteven' // 最好是你的 github 名字 28 | dependencies { 29 | implementation fileTree(dir: 'libs', include: ['*.jar']) 30 | implementation 'com.android.support:appcompat-v7:27.1.1' 31 | api project(':xwebview') 32 | } 33 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /sample/src/main/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | JSBridge Demo 8 | 9 | 36 | 37 | 53 | 54 | 55 | 56 | 57 | 58 |

JSBridge Demo

59 | 60 |
61 |
input fuction name
62 | 63 |
64 | 65 |
66 |
input params
67 | 68 |
69 | 70 | 71 | 72 | 73 | 74 |
75 |
receive msg
76 | 77 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /sample/src/main/java/com/joey/xwebassistant/sample/JavaMethod/JSAsyncFunc.java: -------------------------------------------------------------------------------- 1 | package com.joey.xwebassistant.sample.JavaMethod; 2 | 3 | import com.joey.xwebview.jsbridge.method.JSMessage; 4 | import com.joey.xwebview.jsbridge.method.XJavaMethod; 5 | 6 | import org.json.JSONObject; 7 | 8 | /** 9 | * Description: 10 | * author:Joey 11 | * date:2018/9/5 12 | */ 13 | public class JSAsyncFunc extends XJavaMethod{ 14 | @Override 15 | public JSONObject call(JSMessage message, JSONObject callbackParams) throws Exception { 16 | // async method 17 | new Thread() { 18 | @Override 19 | public void run() { 20 | try { 21 | sleep(3000); 22 | // invoke callback for js 23 | callback(message.callbackID, callbackParams.put("message", "call JSAsyncFunc success")); 24 | } catch (Exception e) { 25 | // error occurred callError 26 | callError(message.callbackID, e.toString()); 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | .start(); 32 | 33 | return null;// return null to tell XWebView not invoke callback right now 34 | } 35 | 36 | @Override 37 | public Permission permission() { 38 | return Permission.PUBLIC; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /sample/src/main/java/com/joey/xwebassistant/sample/JavaMethod/JSToast.java: -------------------------------------------------------------------------------- 1 | package com.joey.xwebassistant.sample.JavaMethod; 2 | 3 | import android.content.Context; 4 | 5 | import com.joey.xwebview.jsbridge.method.XJavaMethod; 6 | 7 | /** 8 | * Description: 9 | * author:Joey 10 | * date:2018/8/21 11 | */ 12 | public abstract class JSToast extends XJavaMethod{ 13 | protected Context context; 14 | 15 | public void setContext(Context context) { 16 | this.context = context; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /sample/src/main/java/com/joey/xwebassistant/sample/JavaMethod/JSToastAuthorized.java: -------------------------------------------------------------------------------- 1 | package com.joey.xwebassistant.sample.JavaMethod; 2 | 3 | import android.text.TextUtils; 4 | import android.widget.Toast; 5 | 6 | import com.joey.xwebview.jsbridge.method.JSMessage; 7 | 8 | import org.json.JSONObject; 9 | 10 | /** 11 | * Description: 12 | * author:Joey 13 | * date:2018/8/20 14 | */ 15 | public class JSToastAuthorized extends JSToast{ 16 | 17 | @Override 18 | public JSONObject call(JSMessage message, JSONObject callbackParams) throws Exception{ 19 | if (TextUtils.isEmpty(message.params.optString("message"))) throw new Exception("no message found from js"); 20 | Toast.makeText(context, message.params.optString("message"), Toast.LENGTH_SHORT).show(); 21 | // return callbackPrams to invoke js callback 22 | return callbackParams.put("message", "invoke JsToastAuthorized success"); 23 | } 24 | 25 | @Override 26 | public Permission permission() { 27 | return Permission.AUTHORIZED; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /sample/src/main/java/com/joey/xwebassistant/sample/JavaMethod/JSToastPrivate.java: -------------------------------------------------------------------------------- 1 | package com.joey.xwebassistant.sample.JavaMethod; 2 | 3 | import android.text.TextUtils; 4 | import android.widget.Toast; 5 | 6 | import com.joey.xwebview.jsbridge.method.JSMessage; 7 | 8 | import org.json.JSONObject; 9 | 10 | /** 11 | * Description: 12 | * author:Joey 13 | * date:2018/8/20 14 | */ 15 | public class JSToastPrivate extends JSToast{ 16 | 17 | @Override 18 | public JSONObject call(JSMessage message, JSONObject callbackParams) throws Exception{ 19 | if (TextUtils.isEmpty(message.params.optString("message"))) throw new Exception("no message found from js"); 20 | Toast.makeText(context, message.params.optString("message"), Toast.LENGTH_SHORT).show(); 21 | return callbackParams.put("message", "invoke JSToastPrivate success"); 22 | } 23 | 24 | @Override 25 | public Permission permission() { 26 | return Permission.PRIVATE; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /sample/src/main/java/com/joey/xwebassistant/sample/JavaMethod/JSToastPublic.java: -------------------------------------------------------------------------------- 1 | package com.joey.xwebassistant.sample.JavaMethod; 2 | 3 | import android.text.TextUtils; 4 | import android.widget.Toast; 5 | 6 | import com.joey.xwebview.jsbridge.method.JSMessage; 7 | 8 | import org.json.JSONObject; 9 | 10 | /** 11 | * Description: 12 | * author:Joey 13 | * date:2018/8/20 14 | */ 15 | public class JSToastPublic extends JSToast{ 16 | 17 | @Override 18 | public JSONObject call(JSMessage message, JSONObject callbackParams) throws Exception{ 19 | if (TextUtils.isEmpty(message.params.optString("message"))) throw new Exception("no message found from js"); 20 | Toast.makeText(context, message.params.optString("message"), Toast.LENGTH_SHORT).show(); 21 | return callbackParams.put("message", "invoke JSToastPublic success"); 22 | } 23 | 24 | @Override 25 | public Permission permission() { 26 | return Permission.PUBLIC; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /sample/src/main/java/com/joey/xwebassistant/sample/SampleActivity.java: -------------------------------------------------------------------------------- 1 | package com.joey.xwebassistant.sample; 2 | 3 | import android.annotation.TargetApi; 4 | import android.net.Uri; 5 | import android.os.Build; 6 | import android.os.Bundle; 7 | import android.support.v7.app.ActionBar; 8 | import android.support.v7.app.AppCompatActivity; 9 | import android.text.TextUtils; 10 | import android.view.View; 11 | import android.webkit.WebSettings; 12 | import android.webkit.WebView; 13 | import android.widget.Button; 14 | import android.widget.EditText; 15 | 16 | import com.joey.xwebassistant.sample.JavaMethod.JSAsyncFunc; 17 | import com.joey.xwebassistant.sample.JavaMethod.JSToast; 18 | import com.joey.xwebassistant.sample.JavaMethod.JSToastAuthorized; 19 | import com.joey.xwebassistant.sample.JavaMethod.JSToastPrivate; 20 | import com.joey.xwebassistant.sample.JavaMethod.JSToastPublic; 21 | import com.joey.xwebview.XWebView; 22 | import com.joey.xwebview.jsbridge.JSBridgeRegister; 23 | import com.joey.xwebview.ui.IWebTitle; 24 | 25 | import java.util.regex.Pattern; 26 | 27 | public class SampleActivity extends AppCompatActivity implements IWebTitle { 28 | 29 | private XWebView webView; 30 | private EditText etUrl; 31 | private EditText etJs; 32 | private boolean authorized; 33 | private String whiteList; 34 | private Pattern whiteListPattern; 35 | private Button btnWhiteList; 36 | private Button btnAuthorized; 37 | 38 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 39 | @Override 40 | protected void onCreate(Bundle savedInstanceState) { 41 | super.onCreate(savedInstanceState); 42 | setContentView(R.layout.activity_sample); 43 | WebView.setWebContentsDebuggingEnabled(true); 44 | etUrl = findViewById(R.id.et_url); 45 | etJs = findViewById(R.id.et_js); 46 | 47 | webView = XWebView.with(findViewById(R.id.wv), this) 48 | .setWebTitleEnable(this) 49 | .setCacheMode(WebSettings.LOAD_NO_CACHE) 50 | .setProgressEnable(findViewById(R.id.progress_bar)) 51 | .setJSBridgeEnabled(register()) 52 | .setJSBridgeAuthorizedChecker(this::isAuthorized) 53 | .loadUrl("file:///android_asset/index.html"); 54 | 55 | etUrl.setText("file:///android_asset/index.html"); 56 | findViewById(R.id.btn_load).setOnClickListener(this::load); 57 | findViewById(R.id.btn_input).setOnClickListener(v-> 58 | webView.invokeJavaScript("msg", "'"+etJs.getText().toString()+"'")); 59 | btnWhiteList = findViewById(R.id.btn_whitelist); 60 | btnWhiteList.setOnClickListener(this::addWhiteList); 61 | btnAuthorized = findViewById(R.id.btn_authorized); 62 | btnAuthorized.setOnClickListener(this::authorized); 63 | } 64 | 65 | private boolean isAuthorized(String javafunc, String url) { 66 | return authorized; 67 | } 68 | 69 | private JSBridgeRegister register() { 70 | JSBridgeRegister register = JSBridgeRegister.create() 71 | .register("toast_public", JSToastPublic.class) 72 | .register("toast_private", JSToastPrivate.class) 73 | .register("toast_authorized", JSToastAuthorized.class) 74 | .register("async_task", JSAsyncFunc.class) 75 | .setMethodInitializer((func, method) -> { 76 | if (method instanceof JSToast) 77 | ((JSToast) method).setContext(SampleActivity.this); 78 | }); 79 | if (!TextUtils.isEmpty(whiteList)) { 80 | register.whiteList(whiteList); 81 | } else if(whiteListPattern != null) { 82 | register.whiteList(whiteListPattern); 83 | } 84 | return register; 85 | } 86 | 87 | @Override 88 | public void onTitleReady(String text) { 89 | ActionBar actionBar = getSupportActionBar(); 90 | if (actionBar != null) { 91 | actionBar.setTitle(text); 92 | } 93 | } 94 | 95 | @Override 96 | public void onBackPressed() { 97 | if (!webView.goBack()) { 98 | super.onBackPressed(); 99 | } 100 | } 101 | 102 | private void load(View view) { 103 | whiteList = "ddd"; 104 | whiteListPattern = Pattern.compile(".*"); 105 | authorized = false; 106 | addWhiteList(view); 107 | authorized(view); 108 | webView.loadUrl(etUrl.getText().toString()); 109 | } 110 | 111 | private void authorized(View view) { 112 | if (!authorized) { 113 | authorized = true; 114 | btnAuthorized.setText("UnAuthorize"); 115 | } else { 116 | authorized = false; 117 | btnAuthorized.setText("Authorize"); 118 | } 119 | } 120 | 121 | private void addWhiteList(View view) { 122 | if (webView.webView().getUrl().contains("android_asset")) { 123 | if (whiteListPattern == null) { 124 | whiteList = null; 125 | whiteListPattern = Pattern.compile("file:///android_asset.*"); 126 | btnWhiteList.setText("remove whitelist"); 127 | } else { 128 | whiteListPattern = null; 129 | btnWhiteList.setText("add whitelist"); 130 | } 131 | 132 | }else { 133 | if (TextUtils.isEmpty(whiteList)) { 134 | whiteListPattern = null; 135 | whiteList = Uri.parse(etUrl.getText().toString()).getHost(); 136 | btnWhiteList.setText("remove whitelist"); 137 | } else { 138 | whiteList = null; 139 | btnWhiteList.setText("add whitelist"); 140 | } 141 | } 142 | 143 | webView.setJSBridgeEnabled(register()) 144 | .setJSBridgeAuthorizedChecker(this::isAuthorized); 145 | webView.reload(); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_sample.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 11 | 17 |