Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF WebBrowser Control and Javascript

15 Jun 2012 1  
One way to get around the invalid character error

Arggggghhh!

I was working on a WPF app in which we're converting XAML "scenes" to HTML. This means we're building the HTML in memory. One of the requirements of the conversion dictates the use of javascript in the rendered HTML scene. The scripts we're using (jQuery and some jQuery code) are fairly lengthy, and I was trying to do this in the HTML:

StringBuilder html = new StringBuilder();
...
string jqueryPath = System.IO.Path.Combine(appPath, "jquery-1.7.2.js"); 
html.AppendFormat("<script type=\"text/javascript\" src=\"{0}\"; ></script>", jqueryPath);

Pretty standard stuff, right? Well, actually, no.

When I navigated to my html stream, I received the error "invalid character at line 1 character 1". If I saved the stream to a HTML file, and loaded it in IE (v9), it worked fine (no error).

The problem is related to security for locally loaded files (if you want to google it, be my guest), and there are three fixes available (that I could find):

  • Add "about:blank" to your Trusted Sites in IE (we couldn't do this because it added one more moving part to the deployment process of the app, and probably compromises security in some as-yet-to-be-determined manner.

  • Create a blank HTML file, load it, and modify the DOM by inserting script elements programatically . We didn't want to do this because there was a possibility we'd forget to add something, and this code also has to eventually be cross-platform.

  • Just bite the bullet and add the script file content as text in the string. This meant we'd have to load the file ourselves, and insert it into the StringBuilder object.

We chose the third option. It was the easiest and posed the fewest possible problems. Your mileage may vary.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here