html - 如何使用 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 中的图像似乎根本没有加载。
我需要帮助,提前谢谢
解决方案
推荐阅读
- ruby-on-rails - Rails 控制台撬“查找”但不显示整个实例
- html - 导航栏使用html和css,a:hover问题
- kubernetes - 普罗米修斯的 Traefik 入口
- python - python上实时更新图形的生成器问题
- java - 独立 IntentService 错误:无法启动服务 Intent {act = com.example.. pkg=com.example.somepkg} U=0:未找到
- testing - 控制台未登录 Web 检查器
- c# - JSON.NET“对象引用未设置为对象的实例”
- r - R中sp地图上的颜色编码空间数据点
- python - Visual Studio 控制台中的 Python 版本
- rxjs - RxJS 操作符“buffer”和“bufferWhen”有什么区别?