【问题标题】:Inject CSS from url Android Studio从 url Android Studio 注入 CSS
【发布时间】:2018-07-16 11:47:02
【问题描述】:

我正在使用 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();

【问题讨论】:

  • 有人可以帮助我吗?

标签: android css webview inputstream inject


【解决方案1】:

如果需要使用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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2015-04-19
    • 2019-05-17
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多