7

I want to have some HTML files with JavaScript loaded into the web browser control in a winforms (v2.0) application. During execution, I won't have internet access, so JavaScript and HTML forms will be embedded in he resources.resx file.

1) how can I load an HTML document out of the resource (analogous to a file:/// operation, but it isn't being loaded from the file system),

2) how would I declare the JavaScript scripts to be loaded? I.e.,

<script src=resource.jquery.min.js??? ... />

Thanks!

SC28
  • 161
  • 1
  • 3
  • 4

2 Answers2

7

To load the HTML document, just compile your html file as embedded resource, and then:

WebBrowser browser = new WebBrowser();
browser.DocumentText = Properties.Resources.<your_html_file>;

If you really need to have external .js files, I think you will probably need to make them embedded resources. Then you can read these resources into a string of javascript.

string GetResourceString(string scriptFile) 
{ 
    Assembly assembly = Assembly.GetExecutingAssembly(); 
    Stream str = assembly.GetManifestResourceStream(scriptFile); 
    StreamReader sr = new StreamReader(str, Encoding.ASCII);
    return sr.ReadToEnd();
}

(Adapted from a reply on this page)

From here, look into IHTMLScriptElement. From what I understand, you may be able to use this javascript string and set it as the ITHMLScriptElement's text field. See this question

Good luck.

Steve
  • 50,173
  • 4
  • 32
  • 41
tronbabylove
  • 1,102
  • 8
  • 12
  • This won't work as is. When built as an Embedded Resource, `Properties.Resources.` will return the contents as a byte array. – nathanchere Aug 18 '15 at 09:04
0

Here's the file structure.

enter image description here

I had success by doing this:

Set the properties of the html files in my solution like this:

Build Action -> Content
Copy to Output Directory -> Copy always

Configure my webBrowser object properties like this:

var myAssembly = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
var path = myAssembly.Substring(0, myAssembly.Length - "MyLib.DLL".Length) + "WebViews/prototype/index.html";
webBrowser.Url = new Uri(path);
goodfriend0
  • 193
  • 1
  • 8
  • 1
    You should use the `System.IO.Path` functions like `GetDirectoryName` here instead of manually slicing with `Substring`. Also note this will result in `file:///` URLs which won't be friendly to ajax-type requests. – emackey Feb 02 '16 at 16:41