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

What is the best way to organize divs in a grid layout that adapts to different screen sizes, similar to the style

Is there a way to align multiple elements of varying heights against the top of a container, similar to what is seen on Wolfram's homepage? I noticed that they used a lot of JavaScript and absolute positioning in their code, but I'm wondering if ...

developing a multimedia player using HTML5

I'm attempting to create a dynamic video "collage" that showcases videos with different aspect ratios in a flexible grid layout. Each row should have videos of the same height, while filling up the horizontal space within a container. With known widt ...

What are the steps for integrating mongoDB with an angular2 application?

I currently have my angular2 & mongoDB setup successfully. While I've managed to read JSON files using the HTTP service, my goal is to create a fully functional application with database connectivity as well. I'm seeking advice on how to con ...

Executing successive setState() calls within a React method: Achieving "synchronous" behavior

During a recent issue in my React application, I encountered a scenario where I needed to make multiple setState() calls within one method and ensure that certain code executed AFTER the states were set. The following code snippet showcases a Dialog box ut ...

Having trouble executing the command ~$ vue add unit-mocha using vue cli 3

I am trying to integrate mocha as a unit testing plugin into my existing Vue project, which was set up using CLI 3 (vue create myProj). This pertains to Vue CLI version 3.0.0 and above, in which my current project is operating. Here is the error message ...

Changing the border color of a Material UI textbox is overriding the default style

Upon the initial page load, I expected the border color of the text box to be red. However, it appeared grey instead. I tried setting the border color to red for all classes but the issue persisted. Even after making changes, the border color remained unch ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...

The jQuery mousedown() function seems to be malfunctioning and unable to trigger the drag event

I am attempting to initiate a drag event using jQuery. You can access the fiddle by clicking here http://jsfiddle.net/sgsvenkatesh/hepbob75/5/ I tried using the following code to initiate the drag event, but it doesn't seem to be working: $(documen ...

The name 'SafeUrl' cannot be located

I'm working on resolving the unsafe warning in the console by using the bypassSecurityTrustUrl method, but unfortunately, I keep encountering an error. user.component.ts import {Component,OnInit} from '@angular/core'; import { DomSanitizer ...

Using Query strings in JavaScript: A Quick Guide

I recently completed a calculator project with only two pages. However, I am struggling to figure out how to pass input field values from one page to another. Despite trying multiple methods, nothing seems to be working. Does anyone know how to successful ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

What is the best way to sort my API responses to display only users who are either currently online or offline?

Hi everyone, I've made great progress on my project so far without any assistance (pretty proud of myself), but now I could use some help. I'm working on creating a tabbed menu that filters the results of my API calls to display: All users, Onlin ...

I am encountering a permission error while trying to show this JSON data

I encountered an error in my code (below) which is logged as: "java.lang.RuntimeException: Unable to open trace file '/sdcard/JsonObject.trace': Permission denied" The first JSON works fine. The issue arises with this JSONArray dataArray = data ...

Organize divs based on their attributes

Using inspiration from this SO post, my goal is to group divs based on their "message-id" attribute. The idea is to wrap all divs with the same "message-id" in a div with the class name "group". <div class="message" message-id="1"> ...

Simultaneously activate the top and bottom stacked components by clicking on them

One of my components has two child components, A and B. Component A is set to position: absolute and placed on top of component B like an overlay. Additionally, component A has a higher z-index. Both components have onClick events attached to them. My que ...

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

Create a new tab that is active and use ng-repeat in the uib-tab directive

I've been trying to solve this problem for a while now. I came across a similar post, but it was left unanswered. So, I decided to create my own post with a Plunkr example. The issue I'm facing is that upon loading, the ui-tab always defaults to ...

automatically changing radio button selection based on dropdown choice

Let's address the issue at hand: I have a dropdown list with over three options, and alongside it, a radio group for yes or no responses. What I am aiming to achieve is setting the radio button to "no" when option 1 is selected, and to "yes" when any ...

Tips for dynamically coloring table cells in Spotfire based on their values

Creating Dynamic Table with HTML After successfully creating a cross table in Spotfire, I now aim to replicate the same table in HTML within a text area. I managed to add values using calculated values, but I'm stuck on how to dynamically set the bac ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...