Commit 1f621801 1f621801ec6b413e4b44e1a2782de8d5dbd4a2c1 by Nicolas Perriault

added Casper.extends() static method for easier extensibility

1 parent e21335d5
......@@ -607,38 +607,37 @@ casper.start('http://foo.bar/', function(self) {
## Extending Casper
Sometimes it can be convenient to add your own methods to the `Casper` class; it's easily doable as illustrated below:
Sometimes it can be convenient to add your own methods to the `Casper` class; it's easily doable using the `Casper.extend()` method as illustrated below:
``` javascript
phantom.injectJs("path/to/casper.js");
phantom.Casper.prototype.fetchTexts = function(selector) {
return this.evaluate(function() {
var elements = document.querySelectorAll(selector);
return Array.prototype.map.call(elements, function(e) {
return e.innerText;
phantom.Casper.extend({
fetchTexts: function(selector) {
return this.evaluate(function() {
var elements = document.querySelectorAll('%selector%');
return Array.prototype.map.call(elements, function(e) {
return e.innerText;
});
}, {
selector: selector.replace("'", "\'")
});
}, {
selector: selector
});
};
},
phantom.Casper.prototype.renderJSON = function(what) {
return this.echo(JSON.stringify(what, null, ' ')).exit();
};
renderJSON: function(what) {
return this.echo(JSON.stringify(what, null, ' ')).exit();
}
});
var articles = [];
new phantom.Casper()
.start('http://www.liberation.fr/', function(self) {
articles = self.fetchTexts('h3');
})
.thenOpen('http://www.lemonde.fr/', function(self) {
articles.concat(self.fetchTexts('h2.article'));
})
.run(function(self) {
self.renderJSON(articles);
})
;
new phantom.Casper().start('http://www.liberation.fr/', function(self) {
articles = self.fetchTexts('h3');
}).thenOpen('http://www.lemonde.fr/', function(self) {
articles.concat(self.fetchTexts('h2.article'));
}).run(function(self) {
self.renderJSON(articles);
});
```
## Licensing
......
......@@ -495,6 +495,18 @@
};
/**
* Extends Casper's prototype with provided one.
*
* @param Object proto Prototype methods to add to Casper
*/
phantom.Casper.extend = function(proto) {
if (typeof(proto) !== "object") {
throw "extends() only accept objects";
}
mergeObjects(phantom.Casper.prototype, proto);
};
/**
* Casper client-side helpers.
*/
phantom.Casper.ClientUtils = function() {
......