Poma Poma - 1 month ago 17
C# Question

How to execute custom JavaScript in WebBrowser control?

I want to apply some styling commands to specific website inside WebBrowser control. The best way to do it is to invoke javascript (I want that style to be editable, with javascript it's easy). I know I can do it with

webBrowser1.Navigate("javascript: alert('hi'); void(0);");
but maximum url length that webBrowser accepts is 502. How to execute longer scripts? Or maybe there is a way to append my CSS to web document?

P.S. I can't edit document's text property since it'll break scripts in this website and I need working copy but just slyled a bit.

Answer

The following post describes how to append a script element to the document HEAD element in a WebBrowser control:

WebBrowser Control from .Net -- How to Inject Javascript?

Code:

    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
    element.text = "function sayHello() { alert('hello') }";
    head.AppendChild(scriptEl);
    webBrowser1.Document.InvokeScript("sayHello");