首页 > 解决方案 > 如何使用 CSS 在 webview 中显示图像

问题描述

在仅显示网页的 Android 应用程序中,我通过 JS 注入在 webview 上应用自定义 CSS。我无法编辑 HTML。使用 CSS,我想在页面上添加一个图像,并在 ::before 伪元素上添加一个背景图像。

我在带有样式编辑器扩展的 Chrome 上尝试了这个,它有效!但是在 Android Studio 中应用相同的 CSS 时,所有代码都可以工作,但图像不显示。

在网页的 HTML 元素上,我应用了 ::before 伪元素。::before 有一个宽度和一个高度,我设置了 background-image:('myurltothepic');

这适用于桌面 Chrome,图像会出现。

在 Android Studio 上,所有注入的 CSS 都按预期工作,除了 URL 中的背景图像。

CSS:

&:before{
    background: url("http://guillaume.work/assets/images/showdown/showdownThk.png") !important;
    content: "";
    width: 80%;
    height: 130px;
    display: block;
    position: relative;
}

爪哇:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    webview =(WebView)findViewById(R.id.webView);
    webview.setWebViewClient(new WebViewClient(){

        String currentUrl;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            currentUrl = url;

            if (url.startsWith("http:") || url.startsWith("https:")) {
                return false;

            }
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {


            // Inject CSS when page is done loading
            injectCSS();

            super.onPageFinished(view, url);
        }
    });

    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setAppCacheEnabled(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setLoadsImagesAutomatically(true);
    webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
    webview.getSettings().setLoadsImagesAutomatically(true);
    webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    webview.loadUrl("https://play.pokemonshowdown.com");
}

// Inject CSS method: read style.css from assets folder
// Append stylesheet to document head
private void injectCSS() {
    try {
        InputStream inputStream = getAssets().open("showdownFancy.css");
        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 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 中的图像似乎根本没有加载。

我需要帮助,提前谢谢

标签: htmlcssandroid-studiomedia

解决方案


推荐阅读