从url Android Studio中注入CSS

时间:2018-02-06 12:00:08

标签: android css webview inputstream inject

我使用InjectCSS脚本在webview上使用额外的css文件。 但是脚本从assets文件夹中获取CSS文件,我希望外部托管的css文件。

    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();
    }
}

我尝试将输入流更改为url但是没有用。

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

1 个答案:

答案 0 :(得分:0)

如果您需要使用BASE64-encode,则需要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();
}