Call javascript function from android activity

I use the following code in the main action, its display of the display () function is undefined

public class cordovaExample extends DroidGap { Context mcontext; private novel n; private Server s; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new Thread(new Server(this)).start(); try { Thread.sleep(500); } catch (InterruptedException e) { } new Thread(new Client()).start(); super.init(); n = new novel(this, appView); s = new Server(this,appView); appView.getSettings().setJavaScriptEnabled(true); appView.addJavascriptInterface(n, "novel"); appView.addJavascriptInterface(s, "Server"); super.loadUrl("file:///android_asset/www/index.html"); super.loadUrl("javascript:display()"); } } 

On the last line, this error display () is not defined

 function display() { alert("abc"); } 

The above code shows the display function that I use in the html file

Any type of help will be appreciated.

+4
source share
2 answers

It is a bad idea to get Cordoba to load JavaScript into the page load. This should be handled by your local JavaScript. Try calling the display () function, as in the HTML page itself:

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

If you need to call JavaScript from Cordoba at any subsequent moment, you can do it like this:

 sendJavascript("display();"); 

To access this method from other classes, you need to access your main activity. An easy, but possibly unsafe method is to create a static variable in your main activity that will keep 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();'); 
+6
source

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

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

And in HTML:

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

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

 @Override public void onResume() { super.onResume(); sendJavascript("display('abc');"); } 
+1
source

Source: https://habr.com/ru/post/1435283/


All Articles