Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted :

 if (url == "https://www.bing.com/search?q=")
    {
        view.evaluateJavascript(
            ("\n"+
                    "windows.addEventListener(load, (event) => {\n" +
                    "  let \"style\" = document.head.appendChild(document.createElement(style));\n" +
                    "  style.innerHTML =\".b_logo:after\" {content:url(https://www.google.ru/images/branding/googlelogo/2x/googlelogo_light_color_92x30dp.png);\n" +
                    "  };\n"+
                    "!important;\n"+
                     "});"),
            null
        )
    }

I initiated it here : override fun onPageFinished(view: WebView, url: String) {

I also attempted :

view.loadDataWithBaseURL("baseURL", "htmlString", "text/html", "UTF-8", null)
        val htmlString = "<html><body><.b_logo:after='https://www.bing.com/rp/tfpoqzYv42r7UjQvzw0PVIoT2nY.png'></body></html>"
        val newHTMLString = htmlString.replace("<.b_logo:after=\"'https://www.bing.com/rp/tfpoqzYv42r7UjQvzw0PVIoT2nY.png'>", "<.b_logo:after='https://www.google.ru/images/branding/googlelogo/2x/googlelogo_light_color_92x30dp.png'>")
        view.loadDataWithBaseURL("baseURL", newHTMLString, "text/html", "UTF-8", null)

Answer №1

One important aspect to consider is ensuring that your JavaScript code executes only after the page has finished loading.

To achieve this, you can create a custom WebViewClient and implement the following method: onPageFinished()

override fun onPageFinished(view: WebView?, url: String?)

Notify the host application when a page completes loading. It's important to note that receiving an onPageFinished() callback doesn't guarantee the update of the DOM. To ensure the current DOM state is ready for rendering, request a visual state callback using WebView#postVisualStateCallback and wait for the callback trigger.

Here's a sample implementation:

fun initWebView() {
    val webView = findViewById<WebView>(R.id.wvTest)
    webView.webViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            // This function gets executed after the page loads
            val javascript = ... // Your JavaScript code here
            view?.evaluateJavascript(javascript) {
                // Log any returned value after running the JavaScript
            }
        }
    }
    webView.settings.javaScriptEnabled = true
    webView.loadUrl("https://www.bing.com/search?q=кму")
}

Ensure that your JavaScript function works correctly on the intended webpage as well.

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

Can a JavaScript framework be created to ensure all browsers adhere to standards?

As someone who isn't an expert in JavaScript, I wonder if it's feasible to create a comprehensive embeddable JavaScript file that ensures all browsers adhere to standards. Could there be a compilation of known JavaScript hacks that compel each br ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Angular Form Validation: Ensuring Data Accuracy

Utilizing angular reactive form to create distance input fields with two boxes labeled as From and To. HTML: <form [formGroup]="form"> <button (click)="addRow()">Add</button> <div formArrayName="distance"> <div *n ...

problem with accessing a website input area

Upon clicking outside the "subheader", I need to display the words "register" and "login" again, unless something is typed into the input fields... that's all there is to it, just click outside the subheader $(document).ready(function() { $(&ap ...

"Utilizing Bootstrap Modal for efficient AJAX saving of multiple records with the help of bootstrapValidator

I'm encountering an issue with a bootstrap modal form and validation using bootstrapValidator. The problem I'm facing is that when I open the modal, fill out the fields, close it, reopen it, refill the fields, and submit the form, my script inser ...

Is it possible to utilize a JavaScript variable as a node in a JSON stringification request?

After successfully retrieving data from the Bungie API previously, I am now facing a challenge in reading a specific JSON file. http://prntscr.com/k3tin3 I'm currently stuck on how to extract a node from the JSON and then utilize it to request charac ...

React's Conditional Rendering

Let's imagine having these initial conditions: this.state = {plans: [], phase: 'daybreak'} along with a dynamic JSON object fetched from an API containing various schedules that may change periodically, for example: plans = {"daybreak": " ...

Encountered an issue while attempting to start an SSR server with inertiajs

I followed all the necessary steps to set up an ssr application, but unfortunately, I am encountering some difficulties. config/inertia export const inertia: InertiaConfig = { view: 'app', ssr: { enabled: true, autoreload: process.en ...

Retrieve a specified quantity of JSON data from an external API

Dealing with a recently received API from an external source: (please note: the data returned is extensive) I'm aware that I can retrieve this large object by using the following method: $.getJSON('https://www.saferproducts.gov/RestWebServices ...

Guide to verifying the property value following mocking a function: Dealing with Assertion Errors in Mocha

Based on a recommendation from a discussion on this link, I decided to mock the readFileSync function and then mocked my outer function. Now, my goal is to verify whether the variable's value has been set as expected. file.js const fs1 = require ...

When calling a method that has been created within a loop, it will always execute the last method of the

In my project, I am utilizing node version 0.8.8 in conjunction with express version 3.0. Within the codebase, there exists an object named checks, which contains various methods. Additionally, there is an empty object called middleware that needs to be p ...

Variables in the $scope object in AngularJS

Within my $scope in angularJS, I am working with two types of variables. 1). $scope.name and $scope.title are linked to input boxes in the UI html code. 2). On the other hand, $scope.sum and $scope.difference are internally used within my JS code. I need ...

Try implementing Underscore/Lodash to organize an object by values and convert it into an array of pairs that can be utilized with AngularJS ng

My goal is to showcase the details from the given object on the user interface using Angular's ng-repeat. It is essential for me to arrange the key/value pairs based on their values and exhibit them in sequential order in an array from highest to lowe ...

Guide to creating dynamic borders around your PHPexcel output

Looking for assistance on adding borders around output arrays in an Excel report using PHPexcel. I reviewed the documentation, but the examples are static, requiring a predefined number to set. My goal is to have all arrays transferred to Excel with bord ...

When attempting to make a post using Prisma's ORM, users may encounter an error message indicating that the post function

Creating a basic prisma application using express and node to query a local mysql database. Encountering an error when calling await prisa.list.create(), details provided below. Here is the script.js code snippet from the HTML page: addItemForm.addEvent ...

Is it true that Safari restricts AJAX Requests following a form submission?

I've developed a JavaScript-based upload progress meter that utilizes the standard multipart submit method instead of submitting files in an iframe. The process involves sending AJAX requests during submission to retrieve the percentage complete of th ...

Prevent duplicate items in an array by utilizing the Map object to add elements

Looking for a way to update an array by adding new values while avoiding duplicates. I've implemented the usage of a Map object to keep track of existing values and tried filtering the new array accordingly. const [items, setItems] = useState([]); ...

What are the benefits of removing event listeners in Reactjs?

In my opinion, the event listeners need to be reliable and consistent. React.useEffect(() => { const height = window.addEventListener("resize", () => { setWindowSize(window.innerHeight); }); return () => window.remov ...

JavaScript animation is not functioning as expected

I created a div with the id of "cen" and gave it a height and width of 50px. $(document).ready(function() { $("#cen").animate({ height: 500px, width: "500px", }, 5000, function() { // Animation complete. }); }); Unfort ...

Guide to implementing a Java-based "back button" for an Appium Android device

The current version of Appium being used is 1.2.0.1 I have come across a couple of code snippets for clicking the back button: // Click back button HashMap swipeObject = new HashMap(); swipeObject.put("keycode", 82); ((JavascriptExecutor)driver).executeS ...