In my project I have a WebView which loads a page (HTML). I want to change all images and show a toast when a user clicks on any image. So I'm adding javascript code which calls Java function:
// code is inside onPageFinished(..) function
JavaScriptInterface jsInterface = new JavaScriptInterface(activity);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
webView.evaluateJavascript(
"var imgs = document.getElementsByTagName('img');" +
"for (var i = 0; i < imgs.length; i++) {" +
"imgs[i].src = 'file:///android_asset/rules_images_placeholder.png';" +
"imgs[i].addEventListener('click', function() {" +
"window.JSInterface.showToast(); " + // <-- isn't called: see logs
"});" +
"} " +
"window.JSInterface.showToast();" // <-- is called
, null);
JavaScriptInterface class:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activity) {
this.activity = activity;
}
@JavascriptInterface
public void showToast(){
Toast.makeText(activity, "Toast message", Toast.LENGTH_SHORT).show();
}
}
showToast()
should be called when 1) page has finished loading 2) user has clicked on image
Problem: showToast()
is called only once - when page has finished loading. When the user clicks on image, showToast()
isn't called, instead the following log appears:
Uncaught TypeError: Cannot read property 'showToast' of undefined", source: (1)
Question: how to call showToast()
on image click?
from Uncaught TypeError: Cannot read property 'showToast' of undefined", source: (1)
No comments:
Post a Comment