Customize your Android WebView to show specific sections of a website

Struggling to display a specific part of a webpage in my webview, despite trying numerous solutions.

https://i.sstatic.net/b185H.png

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
    }
}

In need of assistance as I am new to android development and javaScript. This is required for a college project.

Answer №1

Take a look at my functional code.

private var currentUrl: String = "www.example.com/test"
 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        binding.webviewService.isVerticalScrollBarEnabled = true;
        binding.webviewService.loadUrl(currentUrl)
        val policy = ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
        val document: Document = Jsoup.connect(currentUrl).get()
        document.getElementsByClass("header-area").remove()
        document.getElementsByClass("breadcrumb-area").remove()
        document.getElementsByClass("footer-area").remove()
        val settings: WebSettings = binding.webviewService.settings
        settings.allowUniversalAccessFromFileURLs = true
        settings.javaScriptEnabled = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.cacheMode = WebSettings.LOAD_NO_CACHE
        settings.setAppCacheEnabled(false)
        settings.domStorageEnabled = true

        binding.webviewService.loadDataWithBaseURL(
            currentUrl,
            document.toString(),
            "text/html",
            "utf-8",
            ""
        );


    }

The reference "webview_service" comes from the layout's "WebView" tag. Remember to assign your actual URL to the "currentUrl" variable. You must also include the jsoup library in the dependencies of your build gradle file.

implementation 'org.jsoup:jsoup:1.11.1'

You'll need to identify the HTML tag reference ID from the website that needs to be hidden. In the provided code snippet, the following section is utilized to hide specific parts of the webview:

val document: Document = Jsoup.connect(currentUrl).get()
        document.getElementsByClass("header-area").remove()
        document.getElementsByClass("breadcrumb-area").remove()
        document.getElementsByClass("footer-area").remove()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to redirect to Jade page in Node.js

I recently delved into the world of node js a few days ago. When I click on a button, a function with an ajax call is triggered. function goToUser(){ $.ajax({ url:"/users/UserPage", type:'get', async:false, su ...

What is the best way to instruct jQuery to disregard an empty server response?

After examining this piece of code: $.ajax({ type: "POST", url: theRightUrl, data: whatToPost, logFunction: whatever, suppressSuccessLogging: !0, dataType: "html" }); I encountered an issue where Firefox displays a "no element ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

In Safari, the scrollbar appears on top of any overlays, popups, and modals

On my webpage, I have a div with the CSS property overflow-y: scroll. The page also features several popup modals and overlays. Strangely, the scrollbar of the div appears on top of these overlays instead of behind them. I attempted to resolve this issue b ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

Using conditional statements to render content based on a certain condition within a

One of my requirements is to dynamically render a React component in the following manner: parent.ts ... <Parent> <Child/> <Parent> ... child.ts ... return (someBoolean && <Component/>) ... While ...

What is the best way to create a clickable <li> element from AJAX search results that display dynamic HTML?

Utilizing AJAX technology, I have implemented a live search feature that populates results from a database as the user types in a text field. The results are presented in an unordered list format. My goal is to allow users to click on an item within the li ...

Tips for adjusting the autocomplete maxitem dynamically

I am working on a multi autocomplete feature and I have the following code. Is there a way to dynamically set the maximum number of items based on the value entered in another text field? <script> $(function () { var url2 = "<?php echo SI ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

Converting Custom Data Arrays to JSON using JavaScript

My goal was to create a utility function that can convert custom data (the type of data Sencha Touch stores use) into JSON format. I've made progress, but the function fails when dealing with complex data from the Twitter API, although it works fine w ...

Validate fields by iterating through an object and considering three data points for each field

The struggle is real when it comes to coming up with a title for this question. Suggestions are welcomed! When it comes to field validation, I require three data elements per field: variable name, element ID, and whether it is required or not. Although I ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

I am having trouble getting the color, metalness, lights, and shaders to work properly in Three JS on my

I attempted to create a simple code using Three.js for a red colored torus with a point light and a textured surface, but unfortunately, all I achieved was a black torus that rotates. It seems like the elements in this code are not functioning as expecte ...

Tips for displaying a notification after a successful form submission using jQuery and AJAX

While attempting to submit a PHP form using jquery $.ajax();, I have encountered a peculiar issue. The form is successfully submitted, however, when I try to display an alert message - alert(SUCCESS); on success, it does not work as expected. Any ideas on ...

Utilize three.js to set the camera's position and rotation

In my current setup, I have a particular object in view using a PerspectiveCamera. By utilizing OrbitControls, I can navigate around the object, rotate it, pan it, and more. My goal is to reposition the object to a specific location at a specific angle an ...

Error: The variable success_msg has not been defined in the EJS Reference

I am in the process of developing a library website for my school that includes login and administration capabilities. I am relatively new to node.js and EJS, but I recently revamped the routing and page delivery system to use EJS and express. As part of u ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

Exploring the interactive features of discord.js version 12

Currently, I have a bot set up to log when invites are created, but the logs are only going to a specific channel ID that I designated. I would like to make it so that this can be changed on a per-server basis. Intended Output User: !log channel (CHANNEL ...

Utilizing variable values in Google Charts with AngularJS

Hello everyone, I am attempting to display a chart using data obtained from an API. The output of the API is in the form of List<String> and not in JSON format. Here is the snippet of my JS file: google.load('visualization', '1', ...

What is the method for implementing a Redirect in React Router?

I'm new to React and facing a challenge. My goal is to implement a conditional Redirect, and I have created a function called errorCapture for this purpose. The function should trigger a Redirect based on a specific condition. I have included the ret ...