我在我的Android应用程序中实现了一个webview,并尝试在用户点击布局时突出显示或标记元素。
webview初始化如下:
myWebView.getSettings().setJavaScriptEnabled(true);
//myWebView.getSettings().setGeolocationEnabled(true);
//myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.setWebViewClient(new WebViewController());
尝试标记用户点击的元素,例如在此屏幕截图中:
我通过jsoup获取所有页面div:
doc = Jsoup.connect(url).get();
final Elements alldivs = doc.select("div");
ArrayList<String> list = new ArrayList<String>();
for (org.jsoup.nodes.Element e : alldivs) {
if (!e.id().equals(""))
list.add(e.id());
}
但是如何将选择标记为上面的照片,然后从div id中选择标记的内容。
如何制作这样的东西?
答案 0 :(得分:9)
扩展WebViewClient
和覆盖此处onPageFinished()
,您需要添加自己的js以在每个div
元素上添加点击事件监听器
<强>科特林:强>
class MyWebViewClient : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
view.loadUrl("javascript: " +
"""
Object.prototype.each = function (fn, bind) {
console.log(bind);
for (var i = 0; i < this.length; i++) {
if (i in this) {
fn.call(bind, this[i], i, this);
}
}
};
var _addListener = document.addEventListener || document.attachEvent,
_eventClick = window.addEventListener ? 'click' : 'onclick';
var elements = document.getElementsByTagName("div");
elements.each(function (el) {
_addListener.call(el, _eventClick, function () {
// todo process the clicked div element
el.style.cssText = "border-color: black;border-style: dashed;"
}, false);
})
""".trimIndent())
}
}
<强>爪哇:强>
public class MyWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript: "
+ "Object.prototype.each = function (fn, bind) {\n" +
" console.log(bind);\n" +
" for (var i = 0; i < this.length; i++) {\n" +
" if (i in this) {\n" +
" fn.call(bind, this[i], i, this);\n" +
" }\n" +
" }\n" +
" };\n" +
"\n" +
" var _addListener = document.addEventListener || document.attachEvent,\n" +
" _eventClick = window.addEventListener ? 'click' : 'onclick';\n" +
"\n" +
" var elements = document.getElementsByTagName(\"div\");\n" +
"\n" +
" elements.each(function (el) {\n" +
" _addListener.call(el, _eventClick, function () {\n" +
// todo process the clicked div element
" el.style.cssText = \"border-color: black;border-style: dashed;\"\n" +
" }, false);\n" +
" })");
}
}
现在将webViewClient设置为webView
webview.webViewClient = MyWebViewClient()