I want to inject javascript
file to my site. My site is a simple html
page that is on server. I have injected css
file. (with Manish\'
Some refinements to previous answer. Suppose we use Cyrillic words. Result would be a garbaged strings. It's not good. With code below you can use non-english chars in content. Just add additional url-encoding/decoding to your code and you good to go. Reedited version below.
private void injectJS() {
try {
InputStream inputStream = getAssets().open("jscript.js");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
// preserve non-english letters
String uriEncoded = URLEncoder.encode(new String(buffer, "UTF-8"), "UTF-8").replace("+", "%20");
String encoded = Base64.encodeToString(uriEncoded.getBytes(), Base64.NO_WRAP);
webView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// don't forget to use decodeURIComponent after base64 decoding
"script.innerHTML = decodeURIComponent(window.atob('" + encoded + "'));" +
"parent.appendChild(script)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
Add a new method to inject javascript file.
private void injectJS() {
try {
InputStream inputStream = getAssets().open("jscript.js");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
webView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
Call both methods: injectCSS() and injectJS() after page finishes loading.
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
injectCSS();
injectJS();
super.onPageFinished(view, url);
}
});
I hope this solves the problem.
Be wary of how onload events defined inside inject js file would behave.