Calling javascript function from the android activity

前端 未结 2 2084
终归单人心
终归单人心 2021-01-06 07:59

I am using the following code in the main activity , its giving the function display() is not defined

public class cordovaExample extends DroidGap {
    Cont         


        
相关标签:
2条回答
  • 2021-01-06 08:42

    From Cordova 2.6 you can override onMessage in your CordovaActivity (DroidGap), you have to capture the message "onPageFinished", then you can call any function declared on the document:

    @Override
    public Object onMessage(String id, Object data) {
        if("onPageFinished".equals(id)) {
            sendJavascript("display('abc');");
        }
        return super.onMessage(id, data);
    }
    

    And in the HTML:

    <script>
        function display(arg) {
            alert(arg);
        }
    </script>
    

    Other option is to call it in the onResume() function of the CordovaActivity:

    @Override
    public void onResume() {
        super.onResume();
        sendJavascript("display('abc');");
    }
    
    0 讨论(0)
  • 2021-01-06 08:47

    It's a bad idea to make Cordova load JavaScript on page load. This should be handled by your local JavaScript. Try to call your display() function like this in the HTML page itself:

    <script>
        function display()
        {
    
    
            alert("abc");
    
    
        }
    
        window.onload = function() {
            display();
        }
    </script>
    

    If you need to call a JavaScript from within Cordova at any later point, it is possible to do so this way:

    sendJavascript("display();");
    

    To access this method from other classes, you will need to access your main activity. The easy-but-perhaps-unsafe method is to create a static variable in your main Activity that will hold the activity itself. Example:

    public class MyActivity extends DroidGap {
        public static MyActivity activity;
    
        public void onCreate(Bundle savedInstanceState) {
            activity = this;
        }
    }
    

    Then, from anywhere in your classes, do:

    MyActivity.activity.sendJavascript('display();');
    
    0 讨论(0)
提交回复
热议问题