Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix inject js failed #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.text.TextUtils;


public class InjectedChromeClient extends WebChromeClient {
private final String TAG = "InjectedChromeClient";
private JsCallJava mJsCallJava;
private boolean mIsInjectedJS;
private String mLastPageUrl;

public InjectedChromeClient (String injectedName, Class injectedCls) {
mJsCallJava = new JsCallJava(injectedName, injectedCls);
Expand All @@ -42,13 +44,15 @@ public void onProgressChanged (WebView view, int newProgress) {
//2 OnPageFinished中注入,虽然最后都会全局注入成功,但是完成时间有可能太晚,当页面在初始化调用接口函数时会等待时间过长
//3 在进度变化时注入,刚好可以在上面两个问题中得到一个折中处理
//为什么是进度大于25%才进行注入,因为从测试看来只有进度大于这个数字页面才真正得到框架刷新加载,保证100%注入成功
//
//添加页面url比较是为了避免在某些情况下进度会直接跳过25%及以下, 造成js代码注入失败
if (newProgress <= 25) {
mIsInjectedJS = false;
} else if (!mIsInjectedJS) {
} else if(!mIsInjectedJS || !compareUrls(mLastPageUrl, webview.getUrl())) {
view.loadUrl(mJsCallJava.getPreloadInterfaceJS());
mIsInjectedJS = true;
mLastPageUrl = view.getUrl();
Log.d(TAG, " inject js interface completely on progress " + newProgress);

}
super.onProgressChanged(view, newProgress);
}
Expand All @@ -58,4 +62,12 @@ public boolean onJsPrompt(WebView view, String url, String message, String defau
result.confirm(mJsCallJava.call(view, message));
return true;
}

public static boolean compareUrls(String urlA, String urlB) {
if (TextUtils.isEmpty(urlA)) {
return !TextUtils.isEmpty(urlB);
} else {
return urlA.equals(urlB);
}
}
}