简体   繁体   中英

JavaScript code only works when executed in the developer console

I'm trying to programmatically click a file input button on a website inside of a ChromiumWebBrowser .

However, when the JavaScript code gets executed with ExecuteScriptAsync , nothing happens.

But... when I execute the same line of code in the ChromiumWebBrowser's developer console, the file input button gets clicked and the choose file dialog appears.

using CefSharp;
using CefSharp.WinForms;
using System;
using System.Windows.Forms;

namespace Uploader
{
    public partial class UploaderForm : Form
    {
        private readonly ChromiumWebBrowser webBrowser = new ChromiumWebBrowser("http://tinyupload.com/");

        public ImageIdentificationForm()
        {
            InitializeComponent();
            webBrowser.FrameLoadEnd += WebBrowser_FrameLoadEnd;
            Controls.Add(webBrowser);
        }

        private void WebBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            if (e.Url == webBrowser.Address)
            {
                if (webBrowser.Address == "http://tinyupload.com/")
                {
                    webBrowser.ExecuteScriptAsync("document.querySelector('[name=uploaded_file]').click();");
                    Console.WriteLine("Executed script!");
                }
            }
        }
    }
}

How can I programmatically click the file input button using ExecuteScriptAsync ?

By the way, "Executed script!" gets written in the console. (So... the code IS being executed.)

Are you sure that the button exists at the moment ExecuteScriptAsync method is being called? That button could be created by some JS code. If it's true, something like this might help:

  var button = null;
  do {
    button = document.querySelector('[name=uploaded_file]');
  } while (button == null);
  button.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM