Search code examples
javascriptc#webview2

WebView2 Uncaught TypeError: Cannot read properties of undefined (reading 'click')


I'm trying to run a simple JavaScript on page load completed using the WebView2Samples on GitHub

I knocked up a demo page and loaded that into a WebView2 control and it worked

When I move the script and attempt to load it via C# on a similar webpage I get this error

Uncaught TypeError: Cannot read properties of undefined (reading 'click') at <anonymous>:6:17

webview2-inject-jquery-in-the-current-page says to load the JavaScript in the AddScriptToExecuteOnDocumentCreatedAsyncevent which I've done

Hoping someone can suggest what I'm doing wrong

C#

    private async void WebView2Control_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
    {
        if (!e.IsSuccess)
        {
            MessageBox.Show($"WebView2 creation failed with exception = {e.InitializationException}");
            UpdateTitleWithEvent("CoreWebView2InitializationCompleted failed");
            return;
        }

        this.webView2Control.CoreWebView2.SourceChanged += CoreWebView2_SourceChanged;
        this.webView2Control.CoreWebView2.HistoryChanged += CoreWebView2_HistoryChanged;
        this.webView2Control.CoreWebView2.DocumentTitleChanged += CoreWebView2_DocumentTitleChanged;
        this.webView2Control.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.Image);
        UpdateTitleWithEvent("CoreWebView2InitializationCompleted succeeded");
        string script =  File.ReadAllText(@"D:\Vb\Test\WebView2Samples-main\SampleApps\WebView2WindowsFormsBrowser\Script.js");
        await webView2Control.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script);
    }

JavaScript

var Next = document.getElementsByName("next");
if (typeof(Next) != 'undefined' && Next != null)
  {
      // Exists.
      alert(" Found it");
      NextLink[0].click();
  }
else
  {
      alert("Not Found");

   }

Sample HTML

<table >
    <tr>
    <td>
      <a href="index.html">
        <img name="index" src="../design/images/rsup.png" alt="index"></a>
    </td>
    <td>
      <a href="image2.html">
        <img  name="next" src="../design/images/rsnext.png" alt="next image"></a>
    </td>
    <td>
      <a href="image70.html">
        <img name="last" src="../design/images/rslast.png" alt="last image></a>
    </td>
    </tr>
  </table>

Other attempts of performing the click

       document.getElementsByName("next").click();

  document.getElementsByName("next")[0].click();

With similar error


Solution

  • CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync adds script that will execute whenever a page is loaded before any other script on the page is run and before the DOM is parsed. So you won't be able to use DOM methods to get the next HTML element, because it doesn't exist when your script is run.

    In your injected script you could wrap all that in an event listener that waits for the window DOMContentLoaded event:

    window.addEventListener("DOMContentLoaded", () => {
      var Next = document.getElementsByName("next");
      if (typeof(Next) != 'undefined' && Next != null)
        {
            // Exists.
            alert(" Found it");
            NextLink[0].click();
        }
      else
        {
            alert("Not Found");
        }
    });
    

    Or instead of using AddScriptToExecuteOnDocumentCreatedAsync, you could wait for the CoreWebView2.DOMContentLoaded event and then call ExecuteScriptAsync to inject your script at that point.