1

I have embedded a WebBrowser control in my application and display content that I receive from a server. Specifically: The control is bound to a string which contains the error message from a rest call, that sometimes is HTML.

I wonder if there is a security risk if active content, e.g. JavaScript would be sent as part of the error message. Is there a way to instruct the WebBrowser control to disable all active content?

Johannes Schacht
  • 930
  • 1
  • 11
  • 28
  • Could you please explain more clear? If you want to disable javascript code/html from server you can easily to do. If you trust the server, it even more easier to deal with what server send to you. – NoName Mar 04 '16 at 07:50
  • Quite the opposite. I do not trust the server. I want to display the content in a WebBrowser view but have all active content deactivated. – Johannes Schacht Mar 04 '16 at 08:58
  • Does that mean you want to disable WebBrowser javascript completely? – NoName Mar 04 '16 at 09:09
  • Yes, I want to disable any active content. The whole purpose is to display information that happens to be formatted as HTML. – Johannes Schacht Mar 04 '16 at 11:23

1 Answers1

1

There are several ways to do:

First way is remove javascript from your string before pass it to browser, from Elian Ebbing's answer:

The quick 'n' dirty method would be a regex like this:

var regex = new Regex(
   "(\\<script(.+?)\\</script\\>)|(\\<style(.+?)\\</style\\>)", 
   RegexOptions.Singleline | RegexOptions.IgnoreCase
);

string ouput = regex.Replace(input, "");

The better* (but possibly slower) option would be to use HtmlAgilityPack:

HtmlDocument doc = new HtmlDocument();    doc.LoadHtml(htmlInput);
var nodes = doc.DocumentNode.SelectNodes("//script|//style");
foreach (var node in nodes)       node.ParentNode.RemoveChild(node);
string htmlOutput = doc.DocumentNode.OuterHtml;

*) For a discussion about why it's better, see this thread.

That way seem better and easier.

Second way is use WinForms webbrowser control, which allow you control lower level of browser, but this involve some invoking to WinAPI.

You can see this link for more info.

Community
  • 1
  • 1
NoName
  • 7,940
  • 13
  • 56
  • 108
  • Thank you Sakura. I may need to follow that approach. My thinking was however to instruct the WebBrowser control to disable active content like I can tell it my browser. – Johannes Schacht Mar 04 '16 at 11:59
  • Yes, that would be the best if we can do. But [some people](http://stackoverflow.com/a/10623739/1560697) say it is impossible. – NoName Mar 04 '16 at 12:02
  • @JohannesSchacht Thank :) – NoName Mar 04 '16 at 12:58