tags:

views:

28

answers:

1

Lately, I have ran into the problem with not being able to inject javascript through a webbrowser contol without writing to a new html. Is there a way to inject a string of javascript to the currently browsed webpage?

javascript:(function(){var s=document.createElement('script');s.setAttribute('src','file:///C:/abc.js');document.getElementsByTagName('head')[0].appendChild(s);})()

The current method I am using involves stringbuilder and webbrowser w/ windows.forms.document

string js = @"<script type='text/javascript'>function test(){alert(test)}</script>";
WebBrowser wb = new WebBrowser();
wb.Url = new Uri("http://www.google.com");
wb.Document.Write(js);              
wb.Document.InvokeScript("test");

What am I doing wrong? Is there a better working way of approaching this?

A: 

I would experiment with something like this:

// open google page
wb.Navigate("http://www.google.com")
// search for "stackoverflow"
wb.Navigate("javascript:function x(){document.all.q.value='stackoverflow';document.forms[0].submit();} x();");

Please tell if it works for you (sorry I'm away from Visual Studio at the moment and can't test it)

DK
Your example works! Thanks for the reply. A friend suggested that to me about 2 hours after I posted the question. Is that the only way to inject javascript without writing a new html page?
Nightforce2