Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

With selenium webdriver, I would test html2canvas JS script to take "screenshots" of webpages or parts of it, directly on the browser. I have a written this C# code to test it, but obj is always null.

C# Code for reference

        IWebDriver Driver = new FirefoxDriver();
        Driver.Navigate().GoToUrl("http://www.monsite.com");

        string scriptJS = File.ReadAllText("html2canvas.js");
        scriptJS += @"
            html2canvas(document.body, {
                onrendered: function(canvas) {
                    var img = canvas.toDataURL("image/png");
                    return img;
                }
            });";

        IJavaScriptExecutor executorJS = Driver as IJavaScriptExecutor;
        var obj = executorJS.ExecuteScript(scriptJS);
share|improve this question

1 Answer 1

There are two thinks that are wrong:

  1. return img is value that is retured by onrendered function. That means html2canvas() call doesn't return image as you expect in your code.

  2. executorJS.ExecuteScript returns IWebElement, Int64, Boolean, String, List<IWebElement|Int64|Boolean|String> or null. So you can't get this image as return value, see for more details the doc.

If you need screenshot of site, you can use use ((ITakesScreenshot) driver).GetScreenshot(); (doc).

If you need image in this site, you have to implement it into onrendered function.


UPDATE (25.10.2013)

You can call executorJS.ExecuteAsyncScript. Last parameter in javascript function call will be callback function injected by webdriver. Async method returns after injected method is called, or scriptTimeout is done. For this reason it is a good idea to set timeout to higher value (just to ensure that application is running like expected, later you can put value that is used in productive system).

    Driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5));

    scriptJS += @"
        var webDriverCallback = arguments[arguments.length - 1];

        html2canvas(document.body, {
            onrendered: function(canvas) {
                var img = canvas.toDataURL('image/png').replace('data:image/png;base64,', '');;
                webDriverCallback(img);
            }
        });";

    IJavaScriptExecutor executorJS = Driver as IJavaScriptExecutor;
    var obj = executorJS.ExecuteAsyncScript(scriptJS);

The result is base64 encoded image as String.

share|improve this answer
    
I would test html2canvas because with this script it is possible to take "screenshots" of parts of webpages (Div, ...). This is not possible with ((ITakesScreenshot) driver).GetScreenshot(); –  LeMoussel Sep 26 '13 at 16:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.