Passing Javascript variable for Android activity?

Basically I want to get the data that I already got from javascript and transfer it to Java / Android so that I can work there.

     /* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface {


        @SuppressWarnings("unused")
        public void setX(String html){
            Activity.this.x = html;
            Toast.makeText(myApp, Activity.this.x, Toast.LENGTH_LONG).show();
        }

    }

this works, but I want to be able to name the same Toast string and get the same result. It currently returns null / empty when it is not called through loading via webview.loadUrl ("Javascript:" ...

Any tips?

+1
source share
3 answers

You cannot access javascript stored variables, you must do this through a function call. You should call it from javascript on the html page, for example:

TheNameOfYourInterface.setX('value');

TheNameOfYourInterface javascript, -

YourWebView.addJavascriptInterface(new MyJavaScriptInterface(),"TheNameOfYourInterface");

- , Java .

+2

, , , , calc'd javascript. HTTP GET html/javascript, . , X WebViews, () JavaScript.

+1

I think it would be a good idea to store HTML in Shared Preferences, which is a form of persistent storage. This way you can access it from anywhere.

   //------get sharedPreferences

SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);

//--------modify the value

pref.edit().putString("ToastString", html).commit();

//-------get a value from this from anywhere

String toastValue=pref.getString("ToastString", "");
0
source

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


All Articles