Passing a Javascript Variable to Android Activity?

前端 未结 3 1786
情歌与酒
情歌与酒 2020-12-21 19:00

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 thi         


        
相关标签:
3条回答
  • 2020-12-21 19:04

    I think it will be a good idea to store the HTML in Shared Preferences ,which is a form of persistent storage.This way you will be able to 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 讨论(0)
  • 2020-12-21 19:12

    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.

    0 讨论(0)
  • 2020-12-21 19:14

    I found a different solution to what I need, and I feel like it works for all who do not need get a value calc'd by javascript. My solution to my need was to HTTP GET the html/javascript and then parse it as a string. It saves me some time by not needing to load X WebViews and then (re)creating all my functions in the JavaScript Interface.

    0 讨论(0)
提交回复
热议问题