Edit the CSS styles within a webview

When loading the page in NativeScript using web viewing, I encountered a need to hide certain elements on the page. What is the best way to apply CSS styles to HTML elements in this scenario? Are there any alternatives that could be considered? I have been unable to find a satisfactory answer to my query.

page.xml // XML marking up the page structure

<GridLayout class="page-content">
        <Label row="1" text="{{ result }}" style="text-align:center; z-index:99" />
        <WebView row="2" loaded="onWebViewLoaded" id="myWebView" src="{{ webViewSrc }}"
            style="z-index:1">
        </WebView>
 </GridLayout> 

page.ts // The TypeScript logic for applying styles


export function onDrawerButtonTap(args: EventData) {
    const sideDrawer = <RadSideDrawer>app.getRootView();
    sideDrawer.showDrawer();
}


export function onNavigatingTo(args) {
    const page: Page = <Page>args.object;
    const vm = new Observable();
    vm.set("webViewSrc", "https://m.stoloto.ru/check?int=sitemap");
    vm.set("result", "");
    page.bindingContext = vm;
}
// Handling WebView load finish event
export function onWebViewLoaded(webargs) {
    const page: Page = <Page>webargs.object.page;
    const vm = page.bindingContext;
    const webview: WebView = <WebView>webargs.object;
    vm.set("result", "Loading...");
    vm.set("enabled", false);

    webview.on(WebView.loadFinishedEvent, (args: LoadEventData) => {
        let message = "";
        if (!args.error) {
        } else {
            message = `Error loading, please check your internet connection`;
        }

        vm.set("result", message);
    });
}
// Navigating back to previous page
export function goBack(args) {
    const page: Page = <Page>args.object.page;
    const vm = page.bindingContext;
    const webview: WebView = <WebView>page.getViewById("myWebView");
    if (webview.canGoBack) {
        webview.goBack();
        vm.set("enabled", true);
    }
}
// Navigating forward if possible
export function goForward(args) {
    const page: Page = <Page>args.object.page;
    const vm = page.bindingContext;
    const webview: WebView = <WebView>page.getViewById("myWebView");
    if (webview.canGoForward) {
        webview.goForward();
    } else {
        vm.set("enabled", false);
    }
}

Answer №1

To add custom CSS to a webpage, use JavaScript to create a Style element dynamically after the page has finished loading.

const webView = <WebView>args.object,
    jsStr = `var parent = document.getElementsByTagName('head').item(0);
            var style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = ".-bg-blue {background-color: red !important;}";
            parent.appendChild(style)`;

if (webView.ios) {
    webView.ios.evaluateJavaScriptCompletionHandler(jsStr,
        function (
            result,
            error
        ) {
            if (error) {
                console.log("error...");
            }
        });
} else if (webView.android) {
    // Works only on Android 19 and above
    webView.android.evaluateJavascript(
        jsStr,
        null
    );
}

Check out the Playground Sample here

The code snippet provided changes the background color of elements with the class "-bg-blue" from blue to red on the website .

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

I am disappointed with the lack of functionality in Angular's HTML type inference

When working inside an Angular component, I want to select a div element by id or class. This method works menuDisplayDiv = document.getElementsByClassName("some_class")[0] as HTMLDivElement; menuDisplayDiv = document.getElementById("some ...

Retrieve a collection within AngularFire that includes a subquery

I have the following function getParticipations( meetingId: string ): Observable<Participation[]> { return this.meetingCollection .doc(meetingId) .collection<ParticipationDto>('participations') .snapshotCh ...

Creating a unified environment variable for Angular 2 and ASP.NET Core MVC: A comprehensive guide

In my ASP.NET Core MVC project, I am utilizing an Angular 2 application. Both the Angular 2 app and the Startup.cs file contain code that is specific to different environments. For example, using http://localhost as the web service URL during development ...

The type '{ id: string; }' cannot be assigned to the type 'DeepPartial<T>'

In my code, I am attempting to create a generic function that abstracts my repository infrastructure for creating a where clause. export type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; export int ...

Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt. Rece ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Dealing with typescript error due to snakecase attributes being sent from the database while the frontend only accepts pascalcase attributes

I am facing a challenge regarding converting snake case values from my api to pascal case attributes in the front end. Here is the scenario: Frontend Request Axios request fetching multiple user data, for example: axios.get('/users') API Resp ...

How can we avoid duplicating injectors in a child class when extending a class that already has injected services?

Delving deep into TypeScript inheritance, particularly in Angular 11, I've created a BasePageComponent to encompass all the necessary functions and services shared across pages. However, I've encountered an issue where my base class is becoming b ...

What could be the reason for the TypeScript compiler not recognizing tsconfig.json?

I recently came across a file from a tutorial that has left me confused due to the inconsistency between documentation, tutorials, and examples: /scripts/tsconfig.json: { "compilerOptions": { "emitDecoratorMetadata": true, "experiment ...

saving the MediaObject to Ionic's storage with the set method

I attempted to save a Media Object on ionic storage, but encountered an error message stating: "error while saving media object in storage.set" https://i.sstatic.net/5jEaQ.jpg How can I successfully save a media object using storage.set and retrieve it ...

Sending data from the LoginComponent to the RootComponent

I am facing a challenge with implementing *ngIf to hide the login/logout option in the navbar based on the user's authentication status. When logged in, I want to hide the logout link. Here is my current setup. app.component.ts import { Component, O ...

When integrating external HTML into an Angular 2 component, relative references may become invalid and fail to

My server hosts basic HTML content that includes an image with a relative file location. While this displays correctly in a browser, loading the content using Angular causes issues with resolving the relative path locally. I have tried following suggestio ...

Nested Tagged Union Types in Typescript

Imagine having the following types (syntax similar to Elm/Haskell): type Reply = LoginReply | LogoutReply type LoginReply = LoginSucceeded | AlreadyLoggedIn String When trying to represent this in Typescript using discriminated unions, a challenge arises ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

Managing multiple HTTP requests in Ionic

I am having an issue with my http requests where I only receive the data from the first request and not all of them. Can anyone help me with this problem? Thank you in advance for your assistance. Here is my function: async asyncCall() { return awai ...

My Nextjs project is encountering deployment issues with both Netlify and Heroku

Whenever I attempt to deploy my application on Heroku or Netlify, I encounter an ERROR related to an incorrect import path. It's perplexing because the import is accurate and functions properly locally. Log ./pages/_app.tsx:7:27 6:31:19 PM: Type err ...

What is the best way to search for and isolate an array object within an array of objects using Javascript?

I am attempting to narrow down the list based on offerings const questions = [ { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]}, { "id": 1505, "offerings": [ ...

What is the best way to modify the KeyName in an object?

Having difficulty parsing an Object by changing keynames due to the error message "Element implicitly has an 'any' type because expression of type 'keyof SignInStore' can't be used to index type '{}'". interface SignInSto ...

What causes an error during the compilation of an Angular package containing a singleton class?

I am currently in the process of creating an Angular library. Within this library, I have developed a singleton class to manage the same SignalR connection. Here is the code implementation: import * as signalR from '@microsoft/signalr'; export c ...