I am currently searching for a method to display the content of a URL from an external source. While I have successfully managed to print the title accurately, I am now

I have stripped down most of the elements from my initial code to demonstrate how it is currently functioning. I've successfully implemented a feature that fetches the webview title, but now I am looking to expand it to showcase more of the HTML content or source code. The purpose behind this enhancement is to enable me to print a receipt on a compact thermal printer.

   webview.setWebViewClient(new WebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
        webview.loadUrl("http://www.google.co.uk");

        --------------------------------------------------

          btnPrint.setOnClickListener(new View.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
                @Override
                public void onClick(View v) {
                    try {
                        printData();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });

       --------------------------------------------------

               @RequiresApi(api = Build.VERSION_CODES.O_MR1)
        void printData() throws IOException {

            try {
                String msg = webview.getTitle();
                msg+="\n";
                outputStream.write(msg.getBytes());
                lblPrinterName.setText("Printing Text...");

            } catch (Exception ex){
                ex.printStackTrace();
            }
        }

Answer №1

To implement customized URL loading behavior in Android's WebView, one must create a new class that extends WebViewClient and overrides the shouldOverrideUrlLoading method.

    private class CustomWebViewClient extends WebViewClient {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                URL aURL = new URL(url);
                URLConnection conn = aURL.openConnection(); 
                conn.connect(); 
                InputStream is = conn.getInputStream();
                String htmlContent = readInputStream(is);
                printHtmlContent(htmlContent);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String readInputStream(InputStream inputStream){
            StringBuffer string = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    string.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return string.toString();
        }
    }
    
    webview.setWebViewClient(new CustomWebViewClient());

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

Struggling with serving static content on NodeJS using Express.js

I set up a basic NodeJS and Express server on my development machine running Windows 10. var express = require('express'); var app = express(); app.use(express.static('app')); app.use('/bower_components', express.static(&apo ...

Merge these two NPM packages together

Two npm projects exist: web-api (a library) and UI. The web-api utilizes gRPC-web to interact with the backend before converting it into a simple JavaScript object. In the UI, Vue.js is used in conjunction with web-api. Objective: merge these two project ...

Setting up instagram-node-lib for managing subscriptions

I am currently working on implementing real-time updates for a specific hashtag and displaying the image on the screen. However, I am facing issues setting up my node.js server using the instagram-node-lib module. Even after running the file (node server.j ...

Using a CSS Module Class as a Variable in NextJS

Apologies in advance if I miss any details - this marks my debut post on Stack Overflow. The main objective of the function is to operate my hamburger menu, either opening or closing it. I have shared a snapshot of the JSX file pertaining to this issue: N ...

What is the best way to effectively pass data to a React / NextJS Video component?

I'm currently using a React-based video player that has the following setup: <ReactPlayer playing={true} controls={true} muted={true} loop={true} width="100" height="100" url='videos/330163_SF.mp4' poster="images/ ...

Error encountered while attempting to upload image to firebase as a result of rejecting re-initialization on a class that had previously failed, specifically a java

I am encountering an issue while trying to upload an image from my phone's gallery. After selecting the image, nothing happens and it fails to upload. Even after attempting a clean build and rebuild, the problem persists. The connection abruptly dis ...

Strategies for resolving the DefaultKotlinSourceSetKt initialization issue

While attempting a project build or simple Gradle sync, I encountered the following error: Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSetKt This error occurred after ...

Discovering the Occurrences of each Object in a List using ReactJS

Struggling with arrays of objects in React.js. My list of objects looks like this : const list = [ { name: name1, age: age1, address: addresse1 }, { name: name2, age: age2, address: addresse2 }, { name: name1, age: age1, address: addresse4 }, { name ...

What is causing the javascript in my svg files not to function when embedded in an html document?

I have the following code for an SVG: <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="470px" height="260px" version="1.1" onload="addEvent ...

Concealing HTML pages in Node.js: A step-by-step guide

I have a specific requirement where my website's html pages should only be accessible to users who are logged in. However, when I used the command below, my html pages became public: app.use(express.static('public')); For instance, I do no ...

Adding JSON information into a .js file using ajax technology

I am currently working on integrating a calendar template into my system. In the demo JavaScript file, example events are structured like this: events: [ { id: 1, title: 'Title 1', start: ('2016-01-02'), ...

Tips for locating the li element with the .multiselect class that comes before the one with the active

I have a unique situation where I am working with a list of select boxes. Let's say that the parent element of all the elements in the list is .multiselect, and when a user selects an option, the .active class is added to it. $(".multiselect-contai ...

JQuery Autocomplete Error: Unable to access property 'value' of undefined

I am currently utilizing a jquery autocomplete plugin found here. However, I am encountering an issue when I click on a filtered result, triggering the following error: Uncaught TypeError: Cannot read property 'value' of undefined Upon inspecti ...

What is the best way to execute a function in a different JavaScript file upon receiving a webhook in server.js?

I am currently working on a project that involves using express to handle webhooks sent to a specific URL. The project also includes an index.html file that incorporates the game.js script for a simple tic-tac-toe game. So far, everything is running smooth ...

The closing tag for the "body" element was excluded even though OMITTAG NO was specified

While attempting to validate my contact support page, I encountered the following errors: Omission of end tag for "body", even though OMITTAG NO was specified ✉ You may have forgotten to close an element or intended to self-close an element by ending ...

Ionic, Angular - A component with two out of three inputs displaying undefined values

I am facing an issue with the @input() in my code. Two out of three inputs have undefined values when I try to use them, although they can be displayed using interpolation in the template file. .ts : export class NoteCanvasPageComponent { @Input() note ...

Python Selenium : Struggling to locate element using ID "principal"

As part of my daily work, I am currently working on developing a Python Script that can automate the process of filling out forms on various websites. However, I encountered an issue with Selenium while trying to interact with certain types of webforms. F ...

Getting the current location with react-native-maps: A step-by-step guide

I am attempting to display a map at the user's current geolocation on an Android device using react-native maps. This is my progress so far: import React, { Component } from 'react'; import { View, StyleSheet, Dimensions, } from &ap ...

Implementing AJAX in Rails for the new/create action can greatly enhance the user

I have a timeline with event sections on it that allow you to create, view, update, and delete events directly on the timeline page. Currently, the functionality for deleting an event is working smoothly as the delete section refreshes along with the timel ...

Ways to avoid an infinite loop caused by onAuthStateChanged Firebase Authentication

I have a provider setup that initializes the authentication context from Firebase Auth. Everything is working well, but when I tried to introduce persistence by adding an observer with onAuthStateChanged, it caused an infinite loop. Despite including an u ...