Poma Poma - 1 year ago 155
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 Source

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?


    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
    element.text = "function sayHello() { alert('hello') }";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download