According to the documentation, you need to invoke an existing script defined in the client:
JavaScript:
var extDate = new Date("03 Oct 2013 16:04:19");
function test(date) {
alert(date);
extDate = date;
}
You could also call eval
and run an anonymous function. This would be the preferred method if you have no control over the page source. Essentially, you would be invoking and running code in the JavaScript interpreter.
C#:
private void InvokeTestMethod(DateTime date)
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.Body.AppendChild(webBrowser1.Document.CreateElement("script"));
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { window.date=new Date('03 Oct 2013 16:04:19'); })()");
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { alert(window.newDate.toString()); })()");
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { window.date=new Date('" + date.ToString("dd MMM yyyy HH:mm:ss") + "'); })()");
webBrowser1.Document.InvokeScript("eval", (Object)"(function() { alert(window.newDate.toString()); })()");
}
}
private void Test()
{
InvokeTestMethod(DateTime.Now);
}
VB.NET
Private Sub InvokeTestMethod([date] As DateTime)
If webBrowser1.Document IsNot Nothing Then
webBrowser1.Document.Body.AppendChild(webBrowser1.Document.CreateElement("script"))
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { window.date=new Date('03 Oct 2013 16:04:19'); })()"}))
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { alert(window.newDate.toString()); })()"}))
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { window.date=new Date('" + [date].ToString("dd MMM yyyy HH:mm:ss") + "'); })()"})
webBrowser1.Document.InvokeScript("eval", new [Object]() {"(function() { alert(window.newDate.toString()); })()"}))
End If
End Sub
Private Sub Test()
InvokeTestMethod(DateTime.Now)
End Sub
http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.invokescript.aspx
By using eval, you can invoke anonymous JavaScript functions and run your own code within the context of the web page. In the last two calls to eval, I set the date using DateTime.Now
and format the date in a way that JavaScript can understand.