Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use evaluateJavascript on KitKat and higher #35

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions src/android/RemoteInjectionPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.util.Base64;
import android.os.Build;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebViewEngine;
Expand Down Expand Up @@ -129,23 +130,29 @@ private void injectCordova() {
// Initialize the cordova plugin registry.
jsPaths.add("www/cordova_plugins.js");

// The way that I figured out to inject for android is to inject it as a script
// tag with the full JS encoded as a data URI
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs). The script tag
// is appended to the DOM and executed via a javascript URL (e.g. javascript:doJsStuff()).
StringBuilder jsToInject = new StringBuilder();

for (String path: jsPaths) {
jsToInject.append(readFile(cordova.getActivity().getResources().getAssets(), path));
}
String jsUrl = "javascript:var script = document.createElement('script');";
jsUrl += "script.src=\"data:text/javascript;charset=utf-8;base64,";

jsUrl += Base64.encodeToString(jsToInject.toString().getBytes(), Base64.NO_WRAP);
jsUrl += "\";";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// On KITKAT or higher, use evaluateJavascript to load the JS
webView.getEngine().evaluateJavascript(jsToInject.toString(), null);
} else {
// On lower than KITKAT, inject the full concatenated JS with a
// script tag as a data URI. The script tag is appended to the DOM
// and executed via a javascript URL (e.g. javascript:doJsStuff()).
String jsUrl = "javascript:var script = document.createElement('script');";
jsUrl += "script.src=\"data:text/javascript;charset=utf-8;base64,";

jsUrl += Base64.encodeToString(jsToInject.toString().getBytes(), Base64.NO_WRAP);
jsUrl += "\";";

jsUrl += "document.getElementsByTagName('head')[0].appendChild(script);";
jsUrl += "document.getElementsByTagName('head')[0].appendChild(script);";

webView.getEngine().loadUrl(jsUrl, false);
webView.getEngine().loadUrl(jsUrl, false);
}
}

private String readFile(AssetManager assets, String filePath) {
Expand Down