Call Typescript Function From C# Webbrowser Control
I have WinForm with WebBrowser control where I open HTML5 + Angular JS (TypeScript) form. I want to call typescript function from my C# code but it is not working with InvokeScirpt
Solution 1:
Typescript methods will compile to javascript methods when you build your application, so to call them, you can call compiled methods like any other javascript methods.
Example
In the example, I suppose you have a app.ts
containing this class:
classGreeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return"Hello, " + this.greeting;
}
}
And I suppose you have added app.js
in index.html
add this code:
<html><head><scriptsrc="app.js"></script></head><body>
...
</body></html>
Then in your windows forms application, you can use Greeter
this way:
string javascript = "var greeter = new Greeter('World!'); alert(greeter .greet());";
webBrowser1.Document.InvokeScript("eval", newobject[] { javascript });
Solution 2:
I had a same problem. I wanted to load an Angular 2+ from in WebBrowser control and do form auto fill. So I did as Follow :
- In the head section of index.html of Angular 2+ project I add a javascript function.
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8" /><metaname="viewport"content="width=device-width, initial-scale=1" /><basehref="/" /><title>Test</title><linkrel="icon"type="image/x-icon"href="favicon.ico" /><scripttype="text/javascript">functioncallAngularFunction(params) {window.angularComponentReference.zone.run(function (){window.angularComponentReference.LoginLogout(params); }); }
</script></head><body><app-root>Loading...</app-root></body></html>
- Then in a constructor of a component which I would like the belonging method, response
import { Component, OnInit, NgZone } from'@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
exportclassLoginComponent implements OnInit{
constructor(private ngZone: NgZone){}
ngOnInit() {
window['angularComponentReference'] = { component: this, zone: this.ngZone, LoginLogout: (params) =>this.AutoLogin(params) };
}
public AutoLogin(params: any){
//params could be a string with ',' separator//then assign each parameter to proper variable in this component//which bind to Html fields
}
}
In C#
winWebBrowser.Document.InvokeScript("callAngularFunction", new object[] {"username,password"});
hope it helps.
Post a Comment for "Call Typescript Function From C# Webbrowser Control"