Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.2K
Views
cefsharp ejecutar javascript

Quiero ejecutar código JavaScript usando CefSharp en Windows Forms, pero no funciona. El código es el siguiente y no se muestra la test del mensaje. ¿Me he perdido algo?

 var browser = new ChromiumWebBrowser("http://localhost:50056/simple.aspx"); browser.Name = "Simple Page"; browser.Dock = DockStyle.Fill; this.Controls.Add(browser); browser.ExecuteScriptAsync("alert('test');");
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Debe esperar a que el navegador se haya cargado lo suficiente antes de ejecutar JavaScript. Es tentador comenzar a intentar acceder al DOM en OnFrameLoadStart, mientras que el V8Context se habrá creado y podrá ejecutar un script que el DOM no habrá terminado de cargar. Si necesita acceder al DOM lo antes posible, suscríbase a DOMContentLoaded.

A continuación se muestran algunos ejemplos de ejecución de JavaScript.

 browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); public class RenderProcessMessageHandler : IRenderProcessMessageHandler { // Wait for the underlying JavaScript Context to be created. This is only called for the main frame. // If the page has no JavaScript, no context will be created. void IRenderProcessMessageHandler.OnContextCreated(IWebBrowser browserControl, IBrowser browser, IFrame frame) { const string script = "document.addEventListener('DOMContentLoaded', function(){ alert('DomLoaded'); });"; frame.ExecuteJavaScriptAsync(script); } } //Wait for the page to finish loading (all resources will have been loaded, rendering is likely still happening) browser.LoadingStateChanged += (sender, args) => { //Wait for the Page to finish loading if (args.IsLoading == false) { browser.ExecuteJavaScriptAsync("alert('All Resources Have Loaded');"); } } //Wait for the MainFrame to finish loading browser.FrameLoadEnd += (sender, args) => { //Wait for the MainFrame to finish loading if(args.Frame.IsMain) { args.Frame.ExecuteJavaScriptAsync("alert('MainFrame finished loading');"); } };
over 4 years ago · Santiago Trujillo Report

0

Creo que, en el caso de llamar a una función de JavaScript que existe dentro de HTML y pasar argumentos de entrada, uno puede simplemente usar el evento Browser.LoadingStateChanged en el constructor de MainWindow para asegurarse de que se inicie la carga. Este evento se llamará después de Browser_Loaded, donde se declara el archivo HTML. El siguiente es un ejemplo del código:

 public MainWindow() { InitializeComponent(); //Wait for the page to finish loading (all resources will have been loaded, rendering is likely still happening) Browser.LoadingStateChanged += (sender, args) => { //Wait for the Page to finish loading if (args.IsLoading == false) { Browser.ExecuteScriptAsync("JavaScripFunctionName1", new object[] { arg1, arg2}); } }; } private void Browser_Loaded(object sender, RoutedEventArgs e) { Browser.LoadHtml(File.ReadAllText(GetFilePath("YourHTMLFileName.html"))); }

Sin embargo, si desea ejecutar el código JavaScript y obtener resultados, debe usar:

 var result = await Browser.EvaluateScriptAsync("JavaScripFunctionName2", new object[] { }); MessageBox.Show(result.Result.ToString());

En HTML:

 <html> <body> <script> function JavaScripFunctionName1(arg1, arg2) { // something here } function JavaScripFunctionName2() { // something here return result; } </script> </body> </html>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!