How can I click this button in CasperJS?

26,174

Solution 1

Instead of using the evaluate function and click on your element in the page DOM environment (with jQuery), just use the casper method : this.click('#generate.btn');. It's easier.

There is also the clickLabel() function.

Solution 2

There are three functions available for clicking an element in CasperJS:

  • casper.click():
    • Performs a click on the element matching the provided selector expression.
  • casper.clickLabel():
    • Clicks on the first DOM element found containing label text.
  • casper.thenClick():
    • Adds a new navigation step to click a given selector and optionally add a new navigation step in a single operation.
Share:
26,174
Zee
Author by

Zee

Updated on July 11, 2020

Comments

  • Zee
    Zee almost 4 years

    After some debugging, it appears I'm having difficulty either clicking or triggering the click event of this button within CasperJS:

    <a id="generate" class="btn" href="#generate"><strong>Generate</strong></a>
    

    Here's the code I have so far:

    var casper = require('casper').create({
        clientScripts: [
            '...\\JQuery\\jquery-1.11.1.min.js'
        ],
        pageSettings: {
            userAgent: 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0'
        }
    });
    casper.on('page.initialized', function (page) {
        page.evaluate(function () {
            (function() {
                window.screen = {
                    width: 1600,
                    height: 900
                };
                var fake_nav = {};
                for (var i in navigator) {
                    fake_nav[i] = navigator[i];
                }
                fake_nav.javaEnabled = function() { return true; };
                fake_nav.language = 'en-US';
                window.navigator = fake_nav;
            })();
        });
    });
    casper.start('http://www.json-generator.com/', function() {
        this.echo("Loaded successfully.");
    });
    var template = '[\'{{repeat(1,3)}}\',    {asdf: "hello"}    ]';
    casper.then(function() {
        this.evaluate(function(input) {
            window.$('.CodeMirror')[0].CodeMirror.setValue(input);
         }, template);
    });
    casper.then(function() {
        this.evaluate(function() {
            document.$('#generate').click();
        });
    });
    casper.then(function() {
        var doc = this.evaluate(function($) {
            return window.$('.CodeMirror')[1].CodeMirror.getValue();
        });
        this.echo(doc);
    });
    casper.run(function() {
        this.echo('All Done.');
        this.exit();
    });
    

    This generates the output (note the blank line from the "casper.echo(doc)"):

    Loaded successfully.
    
    All Done.
    

    I've confirmed that my javascript works in the browser console in both Chrome and Firefox. Why can't I click this button in CasperJS?