无法在Android的WebView中检索Javascript方法/对象值

时间:2018-08-16 09:43:39

标签: javascript android

我需要检索以下值,如下图所示: enter image description here

我正在使用此活动在WebView中加载网页:

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {
    WebView browser;
    final Handler myHandler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        CookieSyncManager.createInstance(LoginActivity.this);
        CookieSyncManager.createInstance(getApplicationContext());
        CookieSyncManager.getInstance().sync();
        CookieManager.getInstance().setAcceptCookie(true);

        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        String url = getIntent().getStringExtra("URL");
        String title = getIntent().getStringExtra("TITLE");


        toolbar.setTitle(title);
        browser = findViewById(R.id.browser);
        WebSettings settings = browser.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setJavaScriptEnabled(true);



        browser.addJavascriptInterface(new WebAppInterface(this), "BethubInterface");
        browser.setWebViewClient(new WebViewClient() {


            public void onPageFinished(WebView view, String url) {
                browser.loadUrl("javascript:BethubInterface.SaveUserId(SaveUserId)");
            }
        });
        browser.loadUrl(url);
    }
    public class WebAppInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        WebAppInterface(Context c) {
            mContext = c;
        }

        /** Show a toast from the web page */
        @JavascriptInterface
        public void SaveUserId(String userID) {
            Toast.makeText(mContext, "UserID: " + userID , Toast.LENGTH_SHORT).show();

        }
    }
}

但是,我无法检索方法/对象的值(对不起,我对Javascript不太熟悉”。)我不断收到错误消息:chromium:[INFO:CONSOLE(1)]“未捕获的ReferenceError:SaveUserId为未定义”,来源:(1)

1 个答案:

答案 0 :(得分:0)

您需要将此方法放入某个方法中,然后从Java中调用此方法,如下所示

使用JavaScript

function functionName() {
   BethubInterface.SaveUserId("apptester")
}

在Java中

browser.loadUrl("javascript:functionName()");