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>
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)");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With