What is the process for adding extra CSS to a webpage displayed in WebView2?

Currently, I am utilizing the Webview2 control within a winform application. My goal is to enhance the behavior of the loaded page by injecting additional CSS code when a specific URL is being displayed in the browser control. Specifically, I aim to implement a feature that adds a background color when hovering over any elements on the page.

*:hover {
    background-color: #205081 !important;
}

Is there a way for me to insert this styling directly into the current document's URL?

Although I have been able to achieve similar functionality using Javascript, my attempts to accomplish this through CSS have been unsuccessful so far. Any guidance or tips would be highly appreciated.

 string jsHoverScript = File.ReadAllText("hoverStyle.js");
 await webBrowser.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(jsHoverScript);

Answer №1

As stated in the documentation:

AddScriptToExecuteOnDocumentCreatedAsync
function adds the provided JavaScript to a list of scripts that will be executed after the global object is created, but before the HTML document is parsed and before any other script included by the HTML document is run.

It's important to note that when your script runs, the DOM tree has not been parsed yet, hence any CSS edits won't take effect. Ensure that your script is executed only after the DOM tree has been fully parsed.


  • Option1
    Use window.addEventListener in JavaScript to make sure your actual code runs after the DOM tree is fully parsed.
window.addEventListener('load', 
  function() { 
    // Your main logic here
  }, false
);
  • Option2

To ensure C# code executes after the DOM content is fully loaded, consider using the event CoreWebView2.DOMContentLoaded or similar alternatives. Then, utilize CoreWebView2.ExecuteScriptAsync to execute your main logic.

For further details, check out the following links:
AddScriptToExecuteOnDocumentCreatedAsync Documentation

CoreWebView2.DOMContentLoaded Documentation

CoreWebView2.ExecuteScriptAsync Documentation

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

When utilizing ng-show to display a form, the value of $dirty is constantly false

I am facing an issue with displaying two forms conditionally. I am using ng-show for this purpose. However, I am also trying to implement validation using $dirty but it seems to always be false even when I input a value in the form field. Does anyone have ...

"Trouble arises when event listener fails to function following an append operation

Recently, I delved into the world of HTML/CSS and jQuery in an attempt to create a simple web game. Below is a snippet of my HTML code: function playGame() { var theLine = "<div id = \"line\">"; for (var i = 0; i < 9; ...

Tips for effectively passing generics to React Hooks useReducer

I am currently working with React Hooks useReducer in conjunction with Typescript. I am trying to figure out how to pass a type to the Reducer Function using generics. interface ActionTypes { FETCH, } interface TestPayload<T> { list: T[]; } inter ...

Exploring the power of NodeJS modules through exports referencing

Encountering difficulties referencing dynamic variables related to mongoose models based on user session location value. Two scripts are involved in this process. The first script is called location.js & reporting.js In the location.js script: module.ex ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

swap = with u003d in c sharp

Trying to decode a base-64 string: oKQmwbpPwZGxUGeWQNBucVmNy1JVsxM9uNivn6hpkia+15y3yIemkW8GXW423krf8WNk6yebQixZW78EpPMMtzldQbbsaEmd4aUDCwp78ivOuh83nC8fHy2gwkm5NcS7aaGm2KxkUsWa5ouNUa7BUWPZ3F7LXFR/SLjZRTMY8u7hwYEQCmUQk/zNXsLyHHwZQiOjZfXdb1nC4vu1LItxaw== Tri ...

Setting a default currency value (either in dollars or euros) in an input field

Is there a way to automatically insert a currency symbol (€, $) in a text field by default when entering a number? Are there any default values for this feature? Thank you Here is an example ...

Guide on accessing the fastify application instance within an imported module

Currently, I am working on developing a rest API using Fastify and I am in the process of organizing my code into separate files for better structure. One issue I am facing is how to access the Fastify instance within a file that I import. The following s ...

What is the best method to retrieve the current time in minutes using the Timer component?

I have integrated the react-timer-hook library into my Next.js application to display a timer. The timer is functioning correctly, but I am encountering an issue where I cannot retrieve the current elapsed time in minutes during the handle form event. My g ...

Assign a value to the cookie based on the input from the form

I recently asked a similar question, but it seems like I missed providing some context, which is why I couldn't get it to work. My goal is to set a cookie value of a form entry when clicking on it (using the carhartl jquery plugin), but nothing happen ...

Using PHPs nth-child in media queries

There are multiple images on MyPage, typically displayed in rows of 6. However, the number of images per row adjusts based on browser size using media queries. The issue arises with the margin set for the last image in each row, as the nth-child property r ...

External vendor scripts such as JavaScript and jQuery are not functioning properly after being rendered in a ReactJS environment

I am currently developing a frontend web app using ReactJS. I obtained a template from W3layout that is built with HTML5, CSS3, and custom JS files, along with various third-party/vendor plugins like nice-select, bootstrap, slik, owl-carousel, etc. Despit ...

The concatenation function in JavaScript does not seem to be functioning properly with JSON

My attempt to use .concat() in order to combine two objects is resulting in tiles.concat is not a function The following code (in an angular app and written in coffeescript): $scope.tiles = new UI(); $scope.tiles.loadUITiles(); console.log($sco ...

No constructors are defined for the 'System.Data.SqlClient.SqlDataReader' class

I am encountering an issue with the SqlDataReader in my code. Whenever I try to run the page, I receive the error message "The type 'System.Data.SqlClient.SqlDataReader' has no constructors defined". My goal here is to return a string value of 0 ...

Consistent Errors with AJAX POST Requests Despite CORS Enablement

Here is a function I have created for making an ajax post request: function POST(url, data) { $.ajax({ 'type' : "POST", 'url' : url, 'data' : data, headers : { 'Access-Cont ...

Adjusting font size according to the font style selected

Can conditional font size be determined based on font family using CSS or jQuery? ...

Tips for achieving the Bootstrap 5 Modal Fade Out effect without using jQuery or any additional plugins apart from Bootstrap

I'm facing some challenges in achieving the fade out effect in Bootstrap 5 modals. I am aiming for something similar to the "Fade In & Scale" effect demonstrated here: https://tympanus.net/Development/ModalWindowEffects/ It is crucial for me to accom ...

retrieving information from a secondary window

Currently, I am working on a project and have come across an issue. Please take a look at the following code snippet: <iframe name="stus" id="stus" style="display:none;"></iframe> <form name="water" id="water" method="post" autocomplete="of ...

Tips on confirming the completion of my form when the next button is pressed

I am working on a multi-step form with a jQuery script to split the forms. The first form has only one button - the next button, which takes the client to the next form. However, when I click on the next button in the first form, it moves to the next form ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...