Llamar a una función Javascript en el control C # webBrowser
-
08-07-2019 - |
Pregunta
Estoy usando el control webBrowser en C # para cargar una página web y necesito llamar a una función de JavaScript que devuelve un valor de cadena. Obtuve una solución para usar el método InvokeScript , e intenté mucho, pero todo falló.
Solución
¿Puedes especificar qué falló?
Mi ejemplo a continuación consiste en un formulario con un navegador web y un botón.
El objeto llamado y al final tiene la oración "¡Lo hice!". Entonces conmigo funciona.
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");
}
}
Otros consejos
Puede enviar argumentos a la función js:
// 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"});
}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow