This sample code demonstrates how to inject a .NET object before the page is loaded completely and before all JavaScript on that page is executed. As you can see, the JavaScript code in the <head>
section calls back to the .NET application.
As a result, the injected object will be available to call from JavaScript from any loaded web page or frame, even if a few pages are loaded subsequently.
C#
browser.ScriptContextCreated += (sender, args) => { try { JSValue value = browser.ExecuteJavaScriptAndReturnValue(args.Context.FrameId,"window"); value.AsObject().SetProperty("Account", new Account()); } catch (Exception e) { Debug.WriteLine(e); throw; } }; browser.LoadHTML(@" <html> <head> <script> window.Account.Save('John','Doe'); </script> </head> <body> <h1>Test Page</h1> </body> </html>");
VB.NET
AddHandler browser.ScriptContextCreated, sub(sender, e) Try Dim value As JSValue = browser.ExecuteJavaScriptAndReturnValue(e.Context.FrameId, "window") value.AsObject().SetProperty("Account", New Account()) Catch ex As Exception Debug.WriteLine(ex) Throw End Try End sub browser.LoadHTML(" <html> <head> <script> window.Account.Save('John','Doe'); </script> </head> <body> <h1>Test Page</h1> </body> </html>")
C#
Account.cs
public class Account { public void Save(String firstName, String lastName) { Debug.WriteLine("firstName = " + firstName); Debug.WriteLine("lastName = " + lastName); } }
VB.NET
Account.vb
Public Class Account Public Sub Save(ByVal firstName As String, ByVal lastName As String) Debug.WriteLine("firstName = " & firstName) Debug.WriteLine("lastName = " & lastName) End Sub End Class