使用 JavaScript (Android) 隐藏 WebView 中的元素

问题描述 投票:0回答:1

我正在尝试从加载到 WebView 的网站中删除横幅和页脚。

到目前为止,我的代码运行没有任何问题

但现在的挑战是,当我浏览网站时,例如打开链接,横幅和页脚会显示一秒钟,直到页面完全加载。我知道我只能在加载数据后对其进行操作,因为我无法访问正在加载的网站的服务器,但我认为必须有一种方法来解决这个问题?

我很乐意得到一些想法。

这是迄今为止我的代码:

HomeFragment 类:Fragment() {

private var _binding: FragmentHomeBinding? = null

// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    val homeViewModel =
        ViewModelProvider(this).get(HomeViewModel::class.java)

    _binding = FragmentHomeBinding.inflate(inflater, container, false)
    val root: View = binding.root


    return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val myWebView: WebView = view.findViewById(R.id.webview1)

    fun removeElement(myWebView: WebView ) {

        myWebView.loadUrl("javascript:(function() { document.getElementById('banner').style.display='none';})()")
        myWebView.loadUrl("javascript:(function() { document.getElementsByTagName(\"footer\")[0].style.display='none';})()")
     
    }


    myWebView.webViewClient = object : WebViewClient() {


        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            removeElement(view!!)
        }

    }

    myWebView.loadUrl("The URL I'm loading")
    myWebView.settings.javaScriptEnabled = true
    myWebView.setOnKeyListener { v, keyCode, event ->
        if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
            myWebView.goBack() // Navigate back to previous web page if there is one

        }
        true
    }
    lateinit var swipeRefreshLayout: SwipeRefreshLayout
    swipeRefreshLayout = view.findViewById(R.id.swipe_container)
    swipeRefreshLayout.setOnRefreshListener {
        myWebView.reload()
        swipeRefreshLayout.isRefreshing = false
    }
    

}
override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

}

javascript android dom webview
1个回答
0
投票
  • 您面临的问题是由于网页加载的异步性质造成的。当您导航到新页面时,仅在新页面加载完成后才会执行用于删除横幅和页脚的 JavaScript 代码。这会导致横幅和页脚在隐藏之前显示一小段时间。

  • 使用 WebViewClient 等待页面完全加载,然后再删除横幅和页脚。您可以通过扩展 WebViewClient 类并重写 onPageFinished 方法来实现此目的。

    class HomeFragment : Fragment() {
    
      private var _binding: FragmentHomeBinding? = null
    
      // This property is only valid between onCreateView and
      // onDestroyView.
      private val binding get() = _binding!!
    
      override fun onCreateView(
          inflater: LayoutInflater,
          container: ViewGroup?,
          savedInstanceState: Bundle?
      ): View {
          val homeViewModel =
              ViewModelProvider(this).get(HomeViewModel::class.java)
    
          _binding = FragmentHomeBinding.inflate(inflater, container, false)
          val root: View = binding.root
    
          return root
      }
    
      override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
          super.onViewCreated(view, savedInstanceState)
    
          val myWebView: WebView = view.findViewById(R.id.webview1)
    
          fun removeElement(myWebView: WebView) {
              myWebView.evaluateJavascript("javascript:(function() { document.getElementById('banner').style.display='none';})()", null)
              myWebView.evaluateJavascript("javascript:(function() { document.getElementsByTagName(\"footer\")[0].style.display='none';})()", null)
          }
    
          myWebView.webViewClient = object : WebViewClient() {
    
              private var isPageLoaded = false
    
              override fun onPageFinished(view: WebView?, url: String?) {
                  super.onPageFinished(view, url)
                  if (!isPageLoaded) {
                      removeElement(view!!)
                      isPageLoaded = true
                  }
              }
    
              override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                  isPageLoaded = false
                  return super.shouldOverrideUrlLoading(view, request)
              }
          }
    
          myWebView.loadUrl("The URL I'm loading")
          myWebView.settings.javaScriptEnabled = true
          myWebView.setOnKeyListener { v, keyCode, event ->
              if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
                  myWebView.goBack() // Navigate back to previous web page if there is one
                  isPageLoaded = false
              }
              true
          }
    
          lateinit var swipeRefreshLayout: SwipeRefreshLayout
          swipeRefreshLayout = view.findViewById(R.id.swipe_container)
          swipeRefreshLayout.setOnRefreshListener {
              myWebView.reload()
              swipeRefreshLayout.isRefreshing = false
          }
      }
    
      override fun onDestroyView() {
          super.onDestroyView()
          _binding = null
      }
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.