简体   繁体   中英

How to get the address of a linked Stylesheet in webbrowser control

I have a webbrowser control in a C# winform, which loads the following text:

<head>

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

Can I find the address of the css ( d:/git/ArticleScraper/reports/default.css ) and load it in a textbox editor? It could be a local or online css file with absolute or relative address.

I didn't find any related property or method in the webbrowser control.

WebBrowser control has an event DocumentComplete . It is triggered once your document/file loading has been completed.

First, register to the event:

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

In the event callback, search for "LINK" element tag.

    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 your link:
            link.GetAttribute("href")
        }
    }

The following code will help you. This one is using LINQ query

    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;
        }
    }

The following is a screenshot of the output 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM