将变量从Android传递到在WebView中启动的JavaScript

时间:2013-09-25 09:46:34

标签: javascript android webview

我有一个WebView,点击一个Android按钮就可以将一些JavaScript加载到WebView中。

我的问题是如何在加载时将Android变量传递给JavaScript。

我将当前的JavaScript加载到WebView中的代码

private OnClickListener OnClick_grabit = new OnClickListener() {
    public void onClick(View v) {
        webView.loadUrl("javascript: function loadScript(scriptURL) { 
             var scriptElem = document.createElement('SCRIPT'); 
             scriptElem.setAttribute('language', 'JavaScript'); 
             scriptElem.setAttribute('src', scriptURL); 
             document.body.appendChild(scriptElem);
             } loadScript('http://www.pathtojavascript/javascript.js');");
    }
};

所以我需要将一些内容传递给Android的JavaScript initialize()

5 个答案:

答案 0 :(得分:8)

Java类:

public class JavaScriptInterface {
    Context mContext;
    JavaScriptInterface(Context c) {
        mContext = c;
    }    
    @JavascriptInterface
    public String getFromAndroid() {
        return "This is from android.";
    }
}

Webview代码:

WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient() {});
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

Html和javascript:

<input type="button" value="Get from android" onClick="getFromAndroid()" />
<script type="text/javascript">
    var myVar = null;
    function getFromAndroid() {
        myVar = Android.getFromAndroid();
        alert(myVar);
    }
</script>

答案 1 :(得分:5)

首先,您需要只加载一次脚本(每次都onClick加载),然后调用loadUrl("javascript:initialize(" + myNumber + ");")

答案 2 :(得分:2)

对我有用的正确语法是

StringBuilder buf=new StringBuilder("javascript:testFunction('"+bar+"','"+foo+"')");
Log.d(TAG, "returned string:"+buf.toString());
mWebView.loadUrl(buf.toString());

答案 3 :(得分:0)

您需要在webView中加载urrl,我在之前的应用程序中得到了类似的内容:

webView.loadUrl("javascript:wrapJS.functionName("+value+","+value+")"+);

答案 4 :(得分:0)

将JitPack存储库添加到构建文件

allprojects {
      repositories {
        ...
        maven { url 'https://jitpack.io' }
      }
}

将此添加到app gradle文件:

dependencies {
      compile 'com.github.wendux:WebViewJavascriptBridge:master-SNAPSHOT'
    }

准备你的java脚本:

<!doctype html>
<html><head>
</head><body>
<p>Mehdico</p>
<script>
    function setupWebViewJavascriptBridge(callback) {
        var bridge=window.WebViewJavascriptBridge||window.WKWebViewJavascriptBridge
        if (bridge) { return callback(bridge); }
        var callbacks=window.WVJBCallbacks||window.WKWVJBCallbacks
        if (callbacks) { return callbacks.push(callback); }
        window.WVJBCallbacks=window.WKWVJBCallbacks = [callback];
        if(window.WKWebViewJavascriptBridge){
          window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null)
        }else{
            var WVJBIframe = document.createElement('iframe');
            WVJBIframe.style.display = 'none';
            WVJBIframe.src = 'https://__bridge_loaded__';
            document.documentElement.appendChild(WVJBIframe);
            setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
        }
    }

    setupWebViewJavascriptBridge(function(bridge) {
            bridge.callHandler('sendToJava', { success:'true' }, function(response) {
            })
    })
    </script>
</body></html>

如果你想要更多处理程序,只需复制这些行并更改[jsToJava]和数据部分(success:true)

 bridge.callHandler('sendToJava', { success:'true' }, function(response) {
            })
你的xml中的

        <wendu.webviewjavascriptbridge.WVJBWebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

和java:

webView = findViewById(R.id.webView);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webView.setWebViewClient(new AppWebViewClients((ProgressBar) findViewById(R.id.progressBar)));

    if (Build.VERSION.SDK_INT >= 21) { // for fix invalid https certification
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }

    webView.registerHandler("sendToJava", new WVJBWebView.WVJBHandler() {
        @Override
        public void handler(Object data, WVJBWebView.WVJBResponseCallback callback) {
            Toast.makeText(ActivityPaymentStepBank.this, data.toString(), LENGTH_SHORT).show();
            Log.d("wvjsblog", data.toString());
            callback.onResult(data);
        }
    });

    webView.loadUrl("URL OF YOUR HTML FILE");