【问题标题】:How to pass variable from java to javascript in Android webview?如何在Android webview中将变量从java传递给javascript?
【发布时间】:2021-06-30 06:02:52
【问题描述】:

我已经在 stackoverflow 中看到了一个类似的问题,但我想要对这个问题有更好的解释。我是 android 开发的新手,我想弄清楚如何将我的 java 代码中的变量传递给 index.html 中的 javascript。欢迎提出任何建议。

【问题讨论】:

    标签: android android-webview android-webview-javascript


    【解决方案1】:

    您可以尝试使用 JsBridge 库:

    https://github.com/lzyzsd/JsBridge
    

    【讨论】:

      【解决方案2】:

      试试下面的代码可能对你有帮助。

      //Android WebView code
      JavaScriptInterface JSInterface;
      @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      wv = (WebView)findViewById(R.id.webView1);
      wv.getSettings().setJavaScriptEnabled(true);
      // register class containing methods to be exposed to JavaScript
      JSInterface = new JavaScriptInterface();
      wv.addJavascriptInterface(JSInterface, "JSInterface");
      wv.loadUrl("file:///android_asset/myPage.html");
      }
      
      public class JavaScriptInterface {
      @android.webkit.JavascriptInterface
      public void showToast(String msg)
      {
          Log.d("TAG",msg);
      }
      }
      
      
      
      //This is your web page
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <script type="text/javascript">
             function init()
             {
                var testVal = 'Android Toast!’;
                Android.showToast(testVal);
             }
          </script>
      </head>
      <body>
      <div style="clear: both;height: 3px;"> </div>
        <div>
        <input value="submit" type="button" name="submit"
             id="btnSubmit" onclick="javascript:return init();" />
      </div>
       </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-03
        • 2017-03-20
        • 2017-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多