Execute "native" phantomjs funcs from WebDriver

520 Views Asked by At

I'm developing some web automation tool in C# (.net framework 4). I'm using Selenium webDriver and PhantomJS. It is a really great thing! But sometimes I want to use "native" PhantomJS js-commands like: uploadFile or injectJs Is it possible?

How i use phantomjs now: firs Im starting phantomjs executable using --webdriver= param. Next is:

// connection
private bool ConnectToWebDriver()
        {
            try
            {
                _driver = new RemoteWebDriver(new Uri(localHost+':'+numericPortSelector.Value+"/wd/hub"),
                DesiredCapabilities.PhantomJS());
                _scriptExecutor = _driver as IJavaScriptExecutor;
                _driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(0, 0, (int) numericTimeOut.Value));
                return true;
            }
            catch (Exception)
            {
                return false;
            }  
        }

Thanks!

1

There are 1 best solutions below

0
On

as far as I know, WebDriver does not provide possibilities to call native PhantomJs functions.

1. injectJs

So to get js work I would recommend you the following: investigate JavascriptExecutor workaround:

JavascriptExecutor js = (JavascriptExecutor) driver;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("var x = $(\'"+webElementCSSSelector+"\');");
        stringBuilder.append("x.click();");
        js.executeScript(stringBuilder.toString());

note: this solution works fine for me, but I'm working on JAVA.

2. uploadFile To perform file upload operation try to use Robot + clipboard operation with file location set that is supposed to be uploaded

Robot robot = new Robot();
        String fileToUploadLocation="C:\\test.png";
        setClipboardData(fileToUploadLocation);
        robot.delay(2000);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

  public static void setClipboardData(String str){
        StringSelection stringSelection = new StringSelection(str);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection,null);
    } 

Note: this works fine for me as well, but I work on java. Hope this helps you.