How to replace the internal text content of HTML tags with C #!

I am currently working on the addition of Internet Explorer, which is supposed to scan an HTML document for URLs in plain text, and then “link” them.

I have access to DOM websites, and I had the idea to cross all DOM nodes and look for “links” using RegEx to replace this text with HTML code, however, when I change the “InnerText” property, IHTMLElement object, all of it child nodes are lost, which seriously affects the website.

Here is the code:

//This method is called when IE has finished loading a page
void _webBrowser2Events_DocumentComplete(object pDisp, ref object URL)
{
    if (pDisp == _webBrowser2)
    {
        HTMLDocument pageContent = _webBrowser2.Document;
        IHTMLElement bodyHtmlElmnt = pageContent.body;
        fixElement(bodyHtmlElmnt);
    }   
}

And here is the fixElement method:

void fixElement(IHTMLElement node)
{
    if (node.innerText!=null && ((IHTMLElementCollection)node.children).length==0)
    {
        node.innerText= node.innerText.Replace("testString", "replaceWithThis");
    }

    foreach (IHTMLElement child in (node.children as mshtml.IHTMLElementCollection))
    {
        fixElement(child);
    }
}

This works, but only for nodes that do not have children.

Anyone can help me with this problem, I would be very grateful!

Hi

// Henrik

+3
4

javscript, http://userscripts.org/scripts/review/1352 javascript, #.

webBrowser1.Navigate(new Uri("javascript:<YOURSCRIPT>"));

, , , javascript, .

- script ( , *.js , script)

javascript:(function(){document.body.appendChild(document.createElement('script')).src='<YOUR SCRIPT URL>';})();

javascript, ( :// url)

+2

, ( ),

((IHTMLElementCollection)node.children).length==0

fixElement:

void fixElement(IHTMLElement node)
{
    if (node.innerText!=null) // && ((IHTMLElementCollection)node.children).length==0)
    {
         node.innerText= node.innerText.Replace("testString", "replaceWithThis");
    }
    ...
}
+2

, temp IHTMLElement , .

, .

+1

You should probably use innerText instead of the innerHTML property, and then you can remove this condition: ((IHTMLElementCollection) node.children) .length == 0

+1
source

Source: https://habr.com/ru/post/1766650/


All Articles