How do I add a local script file to the HTML of a WebBrowser control?

IAmAN00B picture IAmAN00B · Oct 27, 2010 · Viewed 15.8k times · Source

This seems really dumb. I've tried a bunch of different ways and it's just not working. I have a WinForms app with a WebBrowser control. If I try with a raw html file on my desktop using the same src string, the src I put together works fine. But plugging the same stuff into the WebBrowser control won't work.

Here's my code:

HtmlElementCollection head = this.wbPreview.Document.GetElementsByTagName( "head" );
if (head != null)
{
    HtmlElement elm = this.webBrowserControl.Document.CreateElement("script");
    string mySource = Environment.CurrentDirectory + @"\MyScriptFile.js";
    elm.SetAttribute("src", mySource);
    elm.SetAttribute("type", "text/javascript");
    ((HtmlElement)head[0]).AppendChild(elm);
}

The WebBrowser doesn't get the script. However, if I change "mySource" to an external resource (via http://), it works fine!

Help!

Answer

womd picture womd · Mar 22, 2012

i came up on your post, while playing around with things following worked for me:

HtmlElementCollection head = webBrowser1.Document.GetElementsByTagName("head");
if (head != null)
{
    HtmlElement elm = webBrowser1.Document.CreateElement("script");
    elm.SetAttribute("type", "text/javascript");
    elm.InnerText = System.IO.File.ReadAllText(Environment.CurrentDirectory + @"\helperscripts.js");
    ((HtmlElement)head[0]).AppendChild(elm);
}

, so all methods of helperscript.js can be invoked using

webBrowser1.Document.InvokeScript("methodname");

, here as a reference for the script invoke: How to inject Javascript in WebBrowser control?

greetings