Search code examples
c#google-chromeprocesscode-injectioninject

Is it possible to open Chrome process and execute javascript on a website in the Chrome window?


For a C# WPF application I'm creating, I would like to open a website in Google Chrome. Chrome is standalone and totally independent from my application. I start Chrome like the following:

Process.Start("chrome.exe", "http://www.example.com");

So an independent process is started, which is the Chrome instance that loads the desired web address.

What I would like to do, is running arbitrary javascript code on the loaded webpage. Like if the javascript code would be 'injected'. I do not control the loaded website.

The purpose is to open a third-party webpage and pre-fill in some form fields so the user doesn't have to do this all time.

Is there any possibility to achieve this?


Solution

  • Yes, I've done this many time using Seleniums's JavaScriptExecutor.
    You'll want to launch Chrome using the Selenium Driver instead of launching the Chrome process yourself.

    https://www.guru99.com/execute-javascript-selenium-webdriver.html

    From their example:

    JavascriptExecutor js = (JavascriptExecutor) driver;  
    js.executeScript(Script,Arguments);