i have implemented a webview in my android app and trying to highlight or to mark element when user click in the layout.
The webview is initialized as following :
myWebView.getSettings().setJavaScriptEnabled(true);
//myWebView.getSettings().setGeolocationEnabled(true);
//myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.setWebViewClient(new WebViewController());
Trying to mark the element which is clicked by user for example like in this screenshot :
I'm getting all the page divs via jsoup :
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());
}
But how to mark the selection as the photo above, and after that select marked content from div id.
How can make some thing like this ?
extend the WebViewClient
and override the onPageFinished()
here you need to add your own js to add click event listener on each div
element
Kotlin:
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())
}
}
Java:
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" +
" })");
}
}
now set your webViewClient to the webView
webview.webViewClient = MyWebViewClient()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With