Skip to content

Commit

Permalink
项目改为gradle构建,作为library推送到maven central 版本v1.1
Browse files Browse the repository at this point in the history
  • Loading branch information
pedant committed Nov 3, 2014
1 parent b6aa04f commit 536ed1a
Show file tree
Hide file tree
Showing 30 changed files with 2,812 additions and 2,264 deletions.
76 changes: 66 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
Safe Java-JS WebView Bridge
===================
抛弃使用高风险的WebView addjavascriptInterface方法,利用onJsPrompt解析纯JSON字符串,来实现网页JS层反射调用Java方法,同时通过对js层调用函数及回调函数的包装,支持方法参数传入所有已知的类型,包括number、string、boolean、object、function。
抛弃使用高风险的WebView addJavascriptInterface方法,利用onJsPrompt解析纯JSON字符串,来实现网页JS层反射调用Java方法,同时通过对js层调用函数及回调函数的包装,支持方法参数传入所有已知的类型,包括number、string、boolean、object、function。

## 如何开始
## 安装
使用Safe Java-JS WebView Bridge最简单的办法就是像下面这样添加项目依赖。

**Maven**

<dependency>
<groupId>cn.pedant.safewebviewbridge</groupId>
<artifactId>library</artifactId>
<version>1.1</version>
<type>aar</type>
</dependency>

**Gradle**

repositories {
mavenCentral()
}

dependencies {
compile 'cn.pedant.safewebviewbridge:library:1.1'
}


## 用法

### 如何开始
初始化Webview WebSettings时允许js脚本执行,同时使用你的注入名和注入类来实例化一个**InjectedChromeClient**对象,然后关联到你的Webview实例。如demo中的例子(页面中引用的对象名为HostApp,指定的注入类为HostJsScope):

WebView wv = new WebView(this);
Expand All @@ -12,16 +37,47 @@ Safe Java-JS WebView Bridge
new InjectedChromeClient("HostApp", HostJsScope.class)
);
wv.loadUrl("file:///android_asset/test.html");
## 方法的定义
需要注入到网页的方法,**必须在注入类中定义为public static且第一个参数接收Webview**,其他参数的类型可以是int、long、double、boolean、String、JSONObject、JsCallback。方法执行时会默认将当前Webview的实例放到第一个参数,所以你的定义可能看起来像这样子的:

### 自定义WebChromeClient子类
如果你需要实现自己的WebChromeClient子类,然后设置到WebView。为了保持InjectedChromeClient的功能,你需要将此类继承自InjectedChromeClient,同时像下面这样覆盖这三个方法。

public class CustomChromeClient extends InjectedChromeClient {

public CustomChromeClient (String injectedName, Class injectedCls) {
super(injectedName, injectedCls);
}

@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
// to do your work
// ...
return super.onJsAlert(view, url, message, result);
}

@Override
public void onProgressChanged (WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
// to do your work
// ...
}

@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// to do your work
// ...
return super.onJsPrompt(view, url, message, defaultValue, result);
}
}

### 方法的定义
需要注入到网页的方法,**必须在注入类中定义为public static且第一个参数接收WebView**,其他参数的类型可以是int、long、double、boolean、String、JSONObject、JsCallback。方法执行时会默认将当前Webview的实例放到第一个参数,所以你的定义可能看起来像这样子的:

public static void testA (WebView webView) {}
网页调用如下:

HostApp.testA();

## 方法的重载
### 方法的重载
在定义时,支持不同参数类型或参数个数的方法重载,如:

public static int overloadMethod(WebView view, int val) {
Expand All @@ -43,12 +99,12 @@ Safe Java-JS WebView Bridge
}
上面这三个方法并没有发生重载,HostApp.overloadMethod(1)调用时只会调用最后一个定义的方法(double类型定义的那个)。

## 方法的返回值
### 方法的返回值
Java层方法可以返回void 或 能转为字符串的类型(如int、long、String、double、float等)或 **可序列化的自定义类型**。关于自定义类型的返回可以参见Demo下“从Java层返回Java对象”项对HostApp.retJavaObject()的调用。另外如果方法定义时返回void,那么网页端调用得到的返回值为null。

如果方法执行过程中出现异常,那么在网页JS端会抛出异常,可以catch后打印详细的错误说明。

## 关于异步回调
### 关于异步回调
举例说明,首先你可以在Java层定义如下方法,该方法的作用是延迟设定的时间之后,用你传入的参数回调Js函数:

public static void delayJsCallBack(WebView view, int ms, final String backMsg, final JsCallback jsCallback) {
Expand All @@ -74,12 +130,12 @@ Java层方法可以返回void 或 能转为字符串的类型(如int、long、
...
}

## 发布时防混淆
### 发布时防混淆
注意注入类中的方法名称不能被混淆,否则页面会调用失败。故发布时需在你的混淆配置文件中加入注入类的防混淆代码,如demo中的HostJsScope配置:

-keepclassmembers class cn.pedant.SafeWebViewBridge.demo.HostJsScope{ *; }

## 小心过大数字
### 小心过大数字
JS中使用过大数字时,可能会导致精度丢失或者错误的数字结果,如下面:

HostApp.passLongType(14102300951321235)
Expand Down
19 changes: 19 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.13.2'
}
}

ext {
compileSdkVersion = 17
buildToolsVersion = "19.1.0"
}

allprojects {
repositories {
mavenCentral()
}
}
14 changes: 14 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
VERSION_NAME=1.1
VERSION_CODE=2
GROUP=cn.pedant.safewebviewbridge

POM_DESCRIPTION=Provide a safe and reliable scheme for Java and JavaScript in Android WebView.
POM_URL=https://github.com/pedant/safe-java-js-webview-bridge
POM_SCM_URL=https://github.com/pedant/safe-java-js-webview-bridge
POM_SCM_CONNECTION=scm:git@github.com:pedant/safe-java-js-webview-bridge.git
POM_SCM_DEV_CONNECTION=scm:git@github.com:pedant/safe-java-js-webview-bridge.git
POM_LICENCE_NAME=The MIT License
POM_LICENCE_URL=http://opensource.org/licenses/MIT
POM_LICENCE_DIST=repo
POM_DEVELOPER_ID=pedant
POM_DEVELOPER_NAME=Pedant
Binary file added gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
6 changes: 6 additions & 0 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.1-all.zip
164 changes: 164 additions & 0 deletions gradlew
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
#!/usr/bin/env bash

##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn ( ) {
echo "$*"
}

die ( ) {
echo
echo "$*"
echo
exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac

# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`

# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option

if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi

# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
Loading

0 comments on commit 536ed1a

Please sign in to comment.