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
- page has finished loading 
- 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:
Question
How to call showToast() on image click?


ifrom within the event handler? Because that would be this problem.window.JSInterfaceis (now)undefined, whereas it had a different value (a reference to your object) earlier. For some reason that changed. I don't think we can tell from what's in the question above what changed, but that's what you want to look for.