Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

java - Passing a Javascript Variable to Android Activity?

Basically I want get data I already have accessed from javascript and passing it to Java/Android so that I can work with it 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 call the same Toast line anywhere and get the same result. Currently it only returns null/empty when not called through loading through webview.loadUrl("Javascript:"...

Any tips?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can not access stored javascript variables, you must do it through a function call. You have to call it from javascript in your html page, for example:

TheNameOfYourInterface.setX('value');

TheNameOfYourInterface will be a javascript object when you add the interface to the webview via

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

so you can do the logic on your webview and call the interface when you set the data so the method in the Java side will be called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...