webview隐藏网页元素
更优雅实现webview元素隐藏显示
背景
因为百度开发者账号遗失,所以才想到之前用石墨文档写过类似的内容,整理一下
实现
自定义类继承webview
重写onDraw方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class H5WebView extends WebView { public H5WebView(Context context) { super(context); }
public H5WebView(Context context, AttributeSet attrs) { super(context, attrs); }
public H5WebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mOnDrawListener != null) { mOnDrawListener.onDrawCallBack(); } }
private OnDrawListener mOnDrawListener;
public void setOnDrawListener(OnDrawListener onDrawListener) { mOnDrawListener = onDrawListener; }
public interface OnDrawListener { public void onDrawCallBack(); } }
|
定义JavaScript
避免繁琐 封装为函数
1 2 3 4 5 6 7 8
| //元素块有id private fun Hide_id_Elements(string: String) { val javascript = ("javascript:function hideId() { " + "document.getElementById(\"$string\").style.display =\"none\"" + "}") web_xs_petReleaseAddress.loadUrl(javascript) web_xs_petReleaseAddress.loadUrl("javascript:hideId();") }
|
1 2 3 4 5 6 7 8
| //元素块只有class private fun Hide_class_Elements(string: String) { val javascript = ("javascript:function hideClass() { " + "document.getElementsByClassName(\"$string\")[0].style.display =\"none\"" + "}") web_xs_petReleaseAddress.loadUrl(javascript) web_xs_petReleaseAddress.loadUrl("javascript:hideClass();") }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| //隐藏方法 private fun hideE() { try { Hide_id_Elements("tool-container") Hide_id_Elements("message-center") Hide_id_Elements("user-center") Hide_id_Elements("newuilogo") Hide_class_Elements("BMap_cpyCtrl BMap_noprint anchorBL") Hide_class_Elements("mapTypeCard panorama choosedType") } catch (e: Exception) { e.printStackTrace() } }
|
调用
web_xs_petReleaseAddress为webview
1 2 3
| web_xs_petReleaseAddress.setOnDrawListener(H5WebView.OnDrawListener { hideE() })
|
注意
document.getElementsByClassName拿到的是数组并非某一个对象 可从console控制台测试看出