Search code examples
javascriptandroidandroid-webviewonkeydown

Android webView evaluateJavaScript executes undefined function


I'm developing an Android application that contains a WebView. I am trying to override onKeyDown activity's method.

I want to call a javascript method everytime phone's backButton is pressed and if the method is undefined I want to execute other native instruction (I want to close the activity).

This is the sense: natively I do this

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (true) {
                    webView.evaluateJavascript(  "try{pageGoBack();}" +
                                                        "catch{window.JSInterface.noBackFunction();}",null);
                    webView.clearCache(true);
                }
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

And for every jsp server side I want to implement something like this:

<script>
        function pageGoBack() {
                       ---do something to go back---
                }
        }
</script>
...

This method had to have the same name "pageGoBack" for every jsp but can have different inner code

That's the fact: before I load one of that jsp with the pageGoBack method everything works (error 'undefined' is catched and JSInterface method is executed).

When I load one of that page the method "remains in cache (???)" and it is always executed (also in those page without it) .

(Look that I also added webView.clearCache(true); but the problem remains)

Thank you -


Solution

  • [SOLVED]

    That was not a problem of Android's WebView or cache. That's a problem of javascript. When a function is defined in as "global" it assumes the global scope when it is evaluated for the first time. So when I visited the .jsp which contains pageGoBack() for the first time the function became globally visible.

    Solution for my case:

    I have lots of jsp with graphic component like this ◄ that means "go back to the previous page". I needed to associate the -jquery button tap function of the current page- to the Android back button. So I:

    • Created an empty css class .empty-class-for-back-button
    • Gave this class to all those ◄ component
    • Made a global js function like this
    function pageGoBack() { 
     var backBtn = $('.empty-class-for-back-button');
     if (backBtn.length > 0){
      backBtn.tap();
     }
     else{
      throw "css class not found";
     }
    }
    
    • Android code is the same I've written in the question

    Exception is now thrown correctly if there is no ◄ element in the current page.

    Hope this can be helpful to somebody.