android webview 返回监听,Android WebView监听并重写网页中window.history.go(-1)方法调用...

import android.annotation.SuppressLint;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.text.TextUtils;

import android.webkit.WebView;

import android.webkit.WebViewClient;

/**

* Created by on 2019/2/22.

* desc:使webview支持window.history.go()

* 使用webview.goBack替换js中的history.go()方法

*/

public class WebViewGoBackSupport {

/**

* 自定义的,当js调用history.go时加载的链接,以监听history.go方法的调用

*/

private final static String CONSTANTS_GO_BACK = "/CONSTANTS_GO_BACK#";

/**

* 当webview不能在返回时回调的方法

*/

@Nullable

private Runnable whenCannotGoBackRunnable;

@NonNull

private WebView webview;

/**

* @param whenCannotGoBackRunnable 当没有上一个页面,而js调用了history.go时回调的方法

*/

@SuppressLint("SetJavaScriptEnabled")

public WebViewGoBackSupport(@NonNull WebView webview, @Nullable Runnable whenCannotGoBackRunnable) {

this.webview = webview;

this.whenCannotGoBackRunnable = whenCannotGoBackRunnable;

this.webview.getSettings().setJavaScriptEnabled(true);

}

/**

* @param whenCannotGoBackRunnable 当没有上一个页面,而js调用了history.go时回调的方法

* @param defaultClient true时,不需要手动调用 onPageFinished、shouldOverrideUrlLoading

*/

public WebViewGoBackSupport(@NonNull WebView webview, @Nullable Runnable whenCannotGoBackRunnable, boolean defaultClient) {

this(webview, whenCannotGoBackRunnable);

if (defaultClient) {

webview.setWebViewClient(new WebViewClient() {

@Override

public void onPageFinished(WebView view, String url) {

WebViewGoBackSupport.this.onPageFinished(url);

super.onPageFinished(view, url);

}

@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) {

WebViewGoBackSupport.this.shouldOverrideUrlLoading(url);

return super.shouldOverrideUrlLoading(view, url);

}

});

}

}

/**

* 在WebViewClient对应方法中调用

* 注:此方法需手动调用,或者使用defaultClient == true

*/

public void onPageFinished(String url) {

//重写js页面window.history.go方法

String script = "javascript:(function(){window.history.go = function(index){" +

"window.location.href='" + CONSTANTS_GO_BACK + "'+index;" +

"}})()";

webview.loadUrl(script);

}

/**

* 在WebViewClient对应方法中调用

* 注:此方法需手动调用,或者使用defaultClient == true

*/

public void shouldOverrideUrlLoading(String url) {

if (!TextUtils.isEmpty(url) && url.contains(CONSTANTS_GO_BACK)) {

int step = -1;

try {

//解析js调用history.go时传入的参数

step = Integer.parseInt(url.split("#")[1]);

} catch (Exception e) {

e.printStackTrace();

}

if (webview.canGoBackOrForward(step)) {

webview.goBackOrForward(step);

} else if (whenCannotGoBackRunnable != null) {

//当没有上一个页面,而js调用了history.go时回调方法

whenCannotGoBackRunnable.run();

}

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值