Reputation: 3675
I have a WebView which in the click of an Android button loads some JavaScript into the WebView.
My question is how would I go about passing an Android variable to the JavaScript when it's loaded.
My Current code to load the JavaScript into the 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');");
}
};
SO I need to pass something to the JavaScript initialize()
from Android.
Upvotes: 10
Views: 25947
Reputation: 2799
Add the JitPack repository to your build file
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Add this to app gradle file:
dependencies {
compile 'com.github.wendux:WebViewJavascriptBridge:master-SNAPSHOT'
}
prepare your java script like this:
<!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>
if you want more handlers just duplicate this lines and change [jsToJava] and data part (success:true)
bridge.callHandler('sendToJava', { success:'true' }, function(response) {
})
in your xml:
<wendu.webviewjavascriptbridge.WVJBWebView
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
and 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");
Upvotes: 0
Reputation: 157
Java Class:
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public String getFromAndroid() {
return "This is from android.";
}
}
Webview code :
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 and 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>
Upvotes: 16
Reputation: 8424
The correct syntax that worked for me is
StringBuilder buf=new StringBuilder("javascript:testFunction('"+bar+"','"+foo+"')");
Log.d(TAG, "returned string:"+buf.toString());
mWebView.loadUrl(buf.toString());
Upvotes: 2
Reputation: 14710
First of all you need to load the script only once (your onClick
is loading it every time), then call loadUrl("javascript:initialize(" + myNumber + ");")
Upvotes: 9
Reputation: 7295
You need to loadUrl in your webView, I got something like this in my previous app:
webView.loadUrl("javascript:wrapJS.functionName("+value+","+value+")"+);
Upvotes: 0