How to pass JSON-formatted data from a WebView to a HTML page

后端 未结 1 1257
无人共我
无人共我 2021-01-11 21:55

I am trying to pass JSON-formatted data from my Android WebView to a HTML page. However, the app crashes whenever I try to parse the original JSON data, which I am expecting

相关标签:
1条回答
  • 2021-01-11 21:56

    I copy pasted your code and it works (nothing is shown because you dont show the data) but the callback made from the Javascript into Android is executed correctly. You can check it with this code:

        WebView mWebView = (WebView) findViewById(R.id.webView1);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(this, "webConnector");
        mWebView.addJavascriptInterface(this, "toaster");
        mWebView.loadUrl("file:///android_asset/table.html");
        }
    
        public String load() {
            Log.e("HelloJavascript","HelloJavascript");
            return "{\"key\":\"data\"}";
        }
    
        public void print(String message){
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    

    And the HTML

        <html>
        <head>
        <title>Test</title>
        <script type="text/javascript">
    
        function loader() {
            var jsonData = window.webConnector.load();
            toaster.print(jsonData);
        }
    
        </script>
        </head>
        <body onload="loader()">
        Do nothing
        </body>
        </html> 
    
    0 讨论(0)
提交回复
热议问题