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:
class Greeter {
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>
<script src="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", new object[] { 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>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<base href="/" />
<title>Test</title>
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<script type="text/javascript">
function callAngularFunction(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'],
})
export class LoginComponent 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"