0

I'm using an InjectCSS script to use an extra css file on a webview. But the script takes the CSS file from the assets folder, I want the css file externally hosted.

    private void injectCSS() {
    try {


        InputStream inputStream = getAssets().open("style.css");

            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();

            String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
            wv.loadUrl("javascript:(function() {" +
                    "var parent = document.getElementsByTagName('head').item(0);" +
                    "var style = document.createElement('style');" +
                    "style.type = 'text/css';" +
                    // Tell the browser to BASE64-decode the string into your script !!!
                    "style.innerHTML = window.atob('" + encoded + "');" +
                    "parent.appendChild(style)" +
                    "})();");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

I tried to change the inputstream to url but that didnt work.

InputStream inputSteam = new URL("http://www.website.com/folder/style.css").openStream();

1 Answers1

0

If you need to use BASE64-encode, you need this

InputStream inputSteam = new URL("http://www.website.com/folder/style.css").openStream();
String encoded  = new String(readBytes(inputStream),  Base64.NO_WRAP);

// ...


public byte[] readBytes(InputStream inputStream) throws IOException {
    // this dynamically extends to take the bytes you read
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

    // this is storage overwritten on each iteration with bytes
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    // we need to know how may bytes were read to write them to the byteBuffer
    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }

    // and then we can return your byte array.
    return byteBuffer.toByteArray();
}
Paul Chu
  • 1,249
  • 3
  • 19
  • 27