You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android WebView如何仅显示网页指定区域?求解决方案

Android WebView 仅显示网页指定区域解决方案

本人是Android开发新手,无JavaScript基础,因大学项目需求,希望让WebView仅显示网页的指定部分(对应截图区域)。尝试了以下代码但未成功,恳请大家提供帮助:

class ActionFragment : Fragment() {
    class MyWebClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageFinished(view: WebView, url: String) {
            view.loadUrl("javascript:document.getElementByClassName('fc-main-container')")

        }
    }
    private var _binding: FragmentActionBinding? = null
        private val binding get() = _binding!!

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view: View = inflater.inflate(R.layout.fragment_action, container, false)

        val mWebView = view.findViewById(R.id.webpage1) as WebView
        mWebView.loadUrl("https://www.webmd.com/diet/healthtool-food-calorie-counter")

        val webSettings = mWebView.settings
        webSettings.javaScriptEnabled = true
        mWebView.webViewClient = MyWebClient()
        return view
    }
}

问题分析

你当前的代码仅通过JavaScript获取了目标元素,但没有执行「隐藏其他内容、只保留目标元素」的核心操作,因此WebView仍会加载并显示整个网页。

修改后的代码

核心修改MyWebClient中的onPageFinished方法,注入完整的JS逻辑来替换页面内容:

class ActionFragment : Fragment() {
    class MyWebClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageFinished(view: WebView, url: String) {
            // 执行JS脚本:仅保留指定类名的元素
            val jsCode = """
                javascript:(function() {
                    // 找到目标元素
                    var targetElement = document.querySelector('.fc-main-container');
                    if (targetElement) {
                        // 将body内容替换为目标元素的完整HTML
                        document.body.innerHTML = targetElement.outerHTML;
                        // 调整body样式,移除多余边距
                        document.body.style.margin = '0';
                        document.body.style.padding = '0';
                        // 可选:给目标元素设置自适应宽度
                        targetElement.style.width = '100%';
                        targetElement.style.boxSizing = 'border-box';
                    }
                })()
            """.trimIndent()
            view.loadUrl(jsCode)
        }
    }

    private var _binding: FragmentActionBinding? = null
    private val binding get() = _binding!!

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view: View = inflater.inflate(R.layout.fragment_action, container, false)

        val mWebView = view.findViewById(R.id.webpage1) as WebView
        mWebView.loadUrl("https://www.webmd.com/diet/healthtool-food-calorie-counter")

        val webSettings = mWebView.settings
        webSettings.javaScriptEnabled = true
        mWebView.webViewClient = MyWebClient()
        return view
    }
}

关键逻辑说明

  1. document.querySelector('.fc-main-container'):通过类名定位你需要显示的目标元素,比getElementByClassName更直接(返回单个元素,无需处理数组)
  2. document.body.innerHTML = targetElement.outerHTML:将整个页面的body内容替换为目标元素的完整代码,实现仅显示指定区域的效果
  3. 样式调整:移除body默认边距,给目标元素设置自适应宽度,避免显示异常

额外提示

如果目标元素是网页异步加载的(比如滚动后才出现),可以延迟执行JS脚本,确保元素已加载:

override fun onPageFinished(view: WebView, url: String) {
    view.postDelayed({
        val jsCode = """
            javascript:(function() {
                // 同上面的JS逻辑
            })()
        """.trimIndent()
        view.loadUrl(jsCode)
    }, 1500) // 延迟1.5秒执行,可根据网页实际加载速度调整
}

内容的提问来源于stack exchange,提问作者PCAPS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:33:30