Getting the URL of a linked Stylesheet within a web browser control

In my C# winform application, I am using a webbrowser control to load some text that includes the following HTML code:

<head>
<link rel="stylesheet" type="text/css" href="d:/git/ArticleScraper/reports/default.css">
</head>

I want to extract the address of the CSS file (

d:/git/ArticleScraper/reports/default.css
) and display it in a textbox editor. The CSS file could be local or online with an absolute or relative address.

Unfortunately, I couldn't find any property or method in the webbrowser control that allows me to do this.

Answer №1

The WebBrowser control in C# has a useful event called DocumentComplete that is fired once your document or file finishes loading.

To make use of this event, you first need to register for it:

webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.WebBrowser1_DocumentCompleted);

Inside the event callback method, you can search for HTML "LINK" elements and retrieve their href attribute:

private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    var browser = sender as WebBrowser;
    var document = browser.Document;

    foreach(HtmlElement link in document.GetElementsByTagName("LINK"))
    {
        // This is where you can access the link's href attribute:
        string href = link.GetAttribute("href");
    }
}

Answer №2

If you're looking to extract a link using LINQ query, the code below will guide you:

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigate(@"D:\DemoFolder\demo.html");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Get a link
        HtmlElement  link = (from HtmlElement element in webBrowser1.Document.GetElementsByTagName("link") select element)
            .Where(x => x.GetAttribute("rel") != null && x.GetAttribute("rel") == "stylesheet" && x.GetAttribute("href") != null).FirstOrDefault();

        if (link != null)
        {
            // Get CSS path
            string path = link.GetAttribute("href");

            textBox1.Text = path;
        }
    }

Take a look at the screenshot of the output: https://i.sstatic.net/ggPge.png

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

PhantomJS in Python Selenium fails to retrieve source code after element click

View the code here import webdriver from selenium driver = webdriver.PhantomJS() driver.get("http://www.metasozluk.com/?r=girdi/goster&g=298794") driver.page_source # The result is a full HTML page. driver.find_element_by_css_selector(".entry-list-c ...

When the button is clicked in Jquery, the HTML is loaded into one div while simultaneously hiding the other div

Looking for some assistance with JQuery, as I am relatively new to it. In my project, I have three divs set up - the first serving as the header, the second containing a slideshow of images along with buttons, and the third that should be displayed upon bu ...

Utilizing two visuals within the <picture> srcset

Is there a way to include two images on the desktop version (one on the right and one on the left) within the picture tag that replaces the mobile version image? I attempted it but it didn't work as expected. <picture> <source medi ...

Create a container-fluid design in Bootstrap with various colors

I am aiming to create a design with a fluid container featuring different background colors on each side, separated by two columns within the container. I have visualized it in this image - do you think it is feasible? https://i.stack.imgur.com/KRc2Q.pn ...

I'm encountering an issue: Uncaught ReferenceError

I am currently working on a to-do list project in javascript, but I keep encountering an error message that says: Uncaught ReferenceError: itemsjson is not defined. After setting my get.item to null, I proceeded to add .push to the code. Can someone pleas ...

Modifying SASS variable values based on the presence of specific text in the page URL

How can I utilize the same SASS file for two different websites with similar functionality but different color schemes? My goal is to dynamically change the color based on the URL of the page. However, I am facing challenges in extracting the page URL from ...

Getting the entire data block in ReactJS: A step-by-step guide

I have encountered an issue with a component I created that only displays the value of block[0], rather than showing the entire block value. For instance, if I input: HI Stackoverflow It only shows "HI" and not the complete content of the field. Is th ...

The syntax error in the Svelte conditional element class is causing issues

Trying to create an if block following the Svelte Guide for if blocks. The process appears straightforward, yet Svelte is flagging it as a syntax error: [!] (svelte plugin) ParseError: Unexpected character '#' public\js\templates\ ...

Display div - conceal div - pause for 15 minutes - continue the cycle

I have a challenging JavaScript task that I've been struggling with for quite some time. The goal is to display a div for 5 seconds, hide it, wait for 15 minutes, then show it again for another 5 seconds, and continue this process in an infinite loop. ...

Tips for locating a DropDownList within a GridView's ItemTemplate without needing to use RowDataBound

I am dealing with a situation where I have a DropDownList located outside of a GridView and another DropDownList inside an ItemTemplate within the GridView. When the SelectedIndex_Changed event is triggered for the outer DropDownList, it should populate th ...

Calculating the total sum of choices within select2

Currently utilizing Select2, a jQuery library, to generate a dropdown list. Trying to determine how to accumulate the values of each option selected by the user. Here's the code sample: <!DOCTYPE html> <html> <head> <m ...

Alter the row's color using the selection feature in the module

Is there a way to change the color of a row when a specific property has a certain value? I found a solution for this issue on Stack Overflow, which can be viewed here: How to color row on specific value in angular-ui-grid? Instead of changing the backgro ...

Retrieving data from an HTML Table using Javascript

I am in the process of designing a dynamic web form that populates from a stored procedure. The form consists of a table with a dropdown list, a text box, and a label. While I can successfully retrieve data from the dropdown and text box, I am facing diffi ...

The radio button that disables other inputs only functions correctly for a single element when using Query Selector, but does not work with Query

I have attempted to develop a form section that is disabled when the user selects option A and enabled when they choose option B. document.getElementById('delivery').onclick = function() { var disabled = document.querySelectorAll(".dis ...

Controlling the Quantity of Selected Checkboxes with JavaScript

I am facing an issue with implementing multiple checkboxes with limits in JavaScript, as shown below. $(".checkbox-limit").on('change', function(evt) { var limit = parseInt($(this).parent().data("limit")); if($(this).siblings(':checked&ap ...

To modify the background of a text, simply click on the image

I recently discovered a helpful hack in an answer on this website, which allows an image to be resized when clicked using the checkbox method. I have successfully implemented this feature but encountered an issue when trying to apply a CSS style change to ...

Ensuring content stays at the bottom of a square div in Bootstrap 4

I am currently developing a budgeting app and I am aiming to create a design with a series of tiles, similar to the one shown below. However, I've encountered an issue where the content I try to add to the tiles ends up sticking to the bottom. Using ...

Obtain all the data in the table cells using Jquery

I've been tasked with a unique challenge. There's a table with a form inside it, and I'm using Jquery to handle the form. Is there a way to retrieve the data from the <td></td> element without any specific id or class? The situa ...

What is the best way to position an element at the bottom of a div?

In the div, there are elements like h1, p, and a. The goal is to have the h1 at the top, the a at the bottom, and the p in the middle regardless of its height. Check out the jsfiddle for a live demo. Here is the source code: HTML <div class="box"> ...

Is there a way to create triangles on all four corners of an image using canvas in JavaScript?

In my code, I am currently working on drawing rectangles on the corners of an image using JavaScript. To achieve this, I first extract the image data from a canvas element. // Get image data let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height) ...