【问题标题】:How can i get a javascript value from webview to android?如何从 webview 获取 javascript 值到 android?
【发布时间】:2015-04-17 09:05:58
【问题描述】:

如果我的 web 视图中存在“注销”类,我正在尝试获取 0 或 1 的值。 (基本想法是,如果我找到“注销”类,则意味着用户已登录,这就是我需要知道的)

到目前为止,我已经搜索并找到了类似的东西。

JavscriptInterface() 类

private static class JavascriptInterface{
    private Map<String,String> valueMap = new HashMap<String,String>();
        public String set(String key, String value){
            valueMap.put(key,  value);
            return "";
        }

        public String get(String key){
            return valueMap.get(key);
        }
}

在 onCreate() 中

webview_mycare = (WebView) findViewById(R.id.webview_mycare);
webview_mycare.getSettings().setJavaScriptEnabled(true);
js = new JavascriptInterface(); 
webview_mycare.addJavascriptInterface(js, "jsinterface");
js.set(JS_KEY, "-1");

    webview_mycare.loadUrl(
                    "javascript:document.function hasClass(element, cls){ return(' '+ element.className +' ').indexOf(' '+ cls +' ')>-1;"
                  + "javascript:document.function var el = document.getElementsByClassName('front-page');"
                  + "javascript:document.function if(hasClass(el,'logout')==true){ "
                  +         "window.jsinterface.set('"+JS_KEY+"','1');"
                  +     "}else{"
                  +         "window.jsinterface.set('"+JS_KEY+"','0');"
                  +     "}"
                );
    try{
        Thread.sleep(200);
    }catch(InterruptedException ex){

        }

    String v=js.get(JS_KEY);
    System.out.println("isMapPage: getValue: value="+v);  
    if("1".equals(v)){  
        Log.e(">>>>>>>>>>>>", "JS_KEY "+ v);
    }else{
        Log.e(">>>>>>>>>>>>", "JS_KEY "+ v);
    }

    webview_mycare.loadUrl(URL);

URL 是一个带有我的网址的字符串

到目前为止,结果是-1。 我写错了什么?

【问题讨论】:

  • 如果您使用 addJavaScriptInterface,请不要忘记使用 @JavascriptInterface 注解并将您的应用程序限制为 Android 4.2+,否则它可能容易受到攻击者的攻击。 developer.android.com/reference/android/webkit/…, java.lang.String)
  • @Robert 好的,我已将 'JavascriptInterface' 重命名为 'JScInterface' 并将 @JavascriptInterface 放在 'onCreate()' 之前,但答案仍然是 -1。我认为我在 javascript 代码中遗漏了一些东西。
  • 你的意思是Activity#onCreate()?不要睡在主线程上。以及在 web 视图中加载了哪个 url?而且,loadUrl() 中的 js 代码看起来像 url 不可用。在您的 PC 浏览器中过去的 js 代码并检查它是否有效。使用js接口的示例很多。
  • 您是否考虑过JavaScript代码可能会异步执行?然后在 JavaScript 代码实际执行之前询问结果。
  • @Robert 对不起,我对此很陌生。

标签: java javascript android webview


【解决方案1】:

试试这个:

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.annotation.SuppressLint;
import android.app.Activity;

public class MainActivity extends Activity implements OnClickListener {

    private static final String URL = "file:///android_asset/index.html";
    private WebView mWebView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.webview); 
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                String user = ((EditText) findViewById(R.id.edit_text)).getText().toString();
                if (user.isEmpty()) {
                    user = "World";
                }
                String javascript="javascript: document.getElementById('msg').innerHTML='Hello "+user+"!';";
                view.loadUrl(javascript);
            }
        });
        refreshWebView();
        findViewById(R.id.button).setOnClickListener(this);
    }

    private void refreshWebView() {
        mWebView.loadUrl(URL);
    }

    @Override
    public void onClick(View v) {
        refreshWebView();
    }

}

还有这个xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:layout_gravity="center"
    android:orientation="vertical">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edit_text"
        android:hint="What is your name?" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="Update Web View"/>

    <WebView 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
        android:layout_weight=".5"
       android:id="@+id/webview" />

</LinearLayout>

【讨论】:

    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 2011-03-18
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多