1

I've created several Powershell scripts that's using the Selenium Webdriver.

Now I need to add some Javascript functionality to one of them, but I'm unable to figure out how I go about to get the syntax correct.

Attempted to convert the following C# code from this discussion: Execute JavaScript using Selenium WebDriver in C#

And this is what my code looks like at the moment:

# Specify path to Selenium drivers
$DriverPath = (get-item ".\" ).parent.parent.FullName + "\seleniumdriver\"
$files = Get-ChildItem "$DriverPath*.dll"

# Read in all the Selenium drivers
foreach ($file in $files) {
    $FilePath = $DriverPath + $file.Name
    [Reflection.Assembly]::LoadFile($FilePath) | out-null
}

# Create instance of ChromeDriver
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver

# Go to example page google.com
$driver.Url = "http://www.google.com"

# Create instance of IJavaScriptExecutor
$js = New-Object IJavaScriptExecutor($driver)

# Run Javascript to get current url title
$title = $js.executeScript("return document.title")

# Write titel to cmd
write-host $title

But I constantly get the error below when creating instance of IJavaScriptExecutor:

"New-Object : Cannot find type [IJavaScriptExecutor]: make sure the assembly containing this type is loaded."

Can anyone figure out what I'm missing? Is it incorrect code? Missing additional dll's?

Br, Christian

Community
  • 1
  • 1
Christian J.
  • 96
  • 2
  • 8

1 Answers1

2

The problem is that IJavaScriptExecutor is an interface and you can't create an instance of an interface. Instead, you need to create an instance of a class which implements the interface. In this case, the ChromeDriver class implements this interface, so you could just skip the line which creates the $js variable and instead use the $driver.

So you'd get something like the following, given that your javascript function works as expected:

# Create instance of ChromeDriver
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver

# Go to example page google.com
$driver.Url = "http://www.google.com"

# Run Javascript to get current url title
$title = $driver.executeScript("return document.title")

You can read more about these classes on the Selenium Documentation.

Robert Westerlund
  • 4,750
  • 1
  • 20
  • 32
  • So I better read up upon how to use instances, interfaces, and classes with Powershell. But for now your example of using the $driver to execute javascript worked as intended. Thank you Robert, much appreciated! – Christian J. Mar 19 '14 at 12:19