首页 > 解决方案 > 如何在 webview 的 java 代码中使用 javascript 值?

问题描述

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {

        webView.evaluateJavascript("alert('hi'); var elem = 
        document.querySelector('.price__container__discount__sales_price').firstChild.innerHTML;" 
        ,null);

        btn.setText(elem);
}

我想在setText方法中使用在js中声明的elem变量到java代码中

标签: javascriptjavaandroidandroid-studiowebview

解决方案


如果您想从加载到 webview 中的 javascript 代码中获取值,我将公开一个带有 @JavascriptInterface 注释的方法,该方法将从您的 javascript 中收集该值。

如何做到这一点的一个例子如下:

本国的

//Make sure to enable these settings
  webviewSettings.setJavaScriptEnabled(true);
  addJavascriptInterface(YOUR_INTERFACE_CLASS, YOUR_INTERFACE_NAME);

 @JavascriptInterface
    public void getSalesPrice(String value) {
        //Here you will get the value from your javascript
    }

JAVASCRIPT

function sendDataToNative(data) {
        YOUR_INTERFACE_NAME.getSalesPrice(data);
    }

推荐阅读