js调试效果:
下面主要是拼装js代码 :
/** * @Description 获取webView选中文字内容 * @param webView* @param callBack*/public static void webViewGetSelectedData(WebView webView,webViewGetSelectedDataCallBack callBack) {String js ="function selectEnable(document) {"+ " document.oncontextmenu = new Function(\"if(event){event.returnValue=true;}\");"+ " document.onselectstart = new Function(\"if(event){event.returnValue=true;}\");"+ " let frames = document.getElementsByTagName(\"iframe\");"+ " if (frames.length > 0) {"+ " for (var i = 0; i < frames.length; i++) {"+ " document = frames[i].contentDocument;"+ " selectEnable(document);"+ " }"+ " }"+ "}"+ "function selectTxt(document) {"+ " let rtnTxt = \"\";"+ " rtnTxt = document.getSelection ? document.getSelection().toString() : document.selection.createRange().text;"+ " let frames = document.getElementsByTagName(\"iframe\");"+ " if (frames.length > 0) {"+ " for (var i = 0; i < frames.length; i++) {"+ " document = frames[i].contentDocument;"+ " let sltTxt = selectTxt(document);"+ " if (sltTxt != \"\") {"+ " rtnTxt = sltTxt;"+ " }"+ " }"+ " }"+ " return rtnTxt;"+ "}"+ "(function(){"+ " selectEnable(document);"+ " return selectTxt(document);"+ "})()";/* android系统4.4以上的时候调用 4.4以下忽略*/webView.evaluateJavascript("javascript:" + js, txt -> {//todo 这里可以对返回文本进行处理,比如转为中文字符,过滤非法字符callBack.onFinished(txt);}); }public interface webViewGetSelectedDataCallBack{/**@param value*/void onFinished(String value);}
至于如何调用,可以通过
@Override
public void onActionModeStarted(ActionMode mode) {……webViewGetSelectedData(webView, value -> { Log.i("getSelection", "getSelectedData: "+value);});……super.onActionModeStarted(mode);
}