Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling javascript function from an android activity

I wan to call a javascript function from an android activity but it doesn't seem to work. I have used the android webview function webview.loadUrl("javascript:function()"); This is my android code:

package com.example.web;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebView;

public class MainActivity extends Activity {

    WebView webview;
    int i=30;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webview = (WebView)findViewById(R.id.webView1);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("file:///android_asset/index.html");
        webview.loadUrl("javascript:change(i)");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

This is my html code:

 <html>
<body>
<div id="texta">text</div>
<script>

function change(num){
document.getElementById("texta").innerHTML=num;
}

</script>

</body>
</html>
like image 336
user2206969 Avatar asked Mar 28 '13 03:03

user2206969


1 Answers

It's likely your page isn't fully loaded by the time you're trying to execute the javascript. Can you try:

webView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        view.loadUrl("javascript:change(i)");
    }
});
like image 180
Tushar Avatar answered Oct 17 '22 10:10

Tushar