Aufruf einer Javascript-Funktion in der C # WebBrowser-Steuerelement
-
08-07-2019 - |
Frage
Ich bin mit dem Web-Browser Kontrolle in C # eine Webseite zu laden und brauchen eine JavaScript-Funktion aufrufen, die einen String-Wert zurückgibt. Ich habe eine Lösung, die die InvokeScript verwenden Methode, und ich versuchte viel, aber alles ist ausgefallen.
Lösung
können Sie angeben, was fehlgeschlagen?
Meine Probe besteht unter einer Form mit einem WebBrowser und einem Knopf.
Das Objekt namens y am Ende den Satz „Ich habe es getan!“. Also bei mir funktioniert es.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentText = @"<html><head>
<script type='text/javascript'>
function doIt() {
alert('hello again');
return 'i did it!';
}
</script>
</head><body>hello!</body></html>";
}
private void button1_Click(object sender, EventArgs e)
{
object y = webBrowser1.Document.InvokeScript("doIt");
}
}
Andere Tipps
Sie können Argumente an die js Funktion senden:
// don't forget this:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentText = @"<html><head>
<script type='text/javascript'>
function doIt(myArg, arg2, arg3) {
alert('hello again ' + myArg);
return 'yes '+arg2+' - you did it! thanks to ' +myArg+ ' & ' +arg3;
}
</script>
</head><body>hello!</body></html>";
}
private void button1_Click(object sender, EventArgs e)
{
// get the retrieved object from js into object y
object y = webBrowser1.Document.InvokeScript("doIt", new string[] { "Snir", "Raki", "Gidon"});
}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow