1

Is it possible to inject javascript into the .NET WebBrowser Windows Forms control? If so, how would I go about doing this?

Kev
  • 118,037
  • 53
  • 300
  • 385
ali
  • 21
  • 1
  • 2
  • Your question is totally misleading. Please make it more understandable. Honestly - no idea what do you want . You want to add js file to visual studio? programmatically add script to the page? something else? – chaZm Aug 09 '11 at 11:27
  • He has a webbrowser control in his C# forms app, and would like to modify each page it visits by adding an external JS file. – TJHeuvel Aug 09 '11 at 11:28
  • when you want to do that? If you do it too early the document may not be ready for manipulation, if you do it too late, the document may be in an always manipulating mode (see twitter) – Sheng Jiang 蒋晟 Aug 09 '11 at 15:33

1 Answers1

1

You can execute any javascript you want from the WebBrowser control. See an example here.

I'd recommend doing something like this in javascript to load an external js file:

var element = document.createElement('script');
element.setAttribute('type', 'text/javascript');
element.setAttribute('src', 'http://code.jquery.com/jquery-1.6.2.min.js');
document.getElementsByTagName('head')[0].appendChild(element);

I'm loading JQuery specifically here.

I believe you can just call yourBrowser.Document.InvokeScript() and pass a huge JS string in to do whatever you want.

UPDATE:

A comment pointed out you can only call existing JS functions with InvokeScript. Turns out you can do something similar in C#.

See the top answer on this SO link.

Community
  • 1
  • 1
jonathanpeppers
  • 26,115
  • 21
  • 99
  • 182