Introduction
I'm trying to write some extensions to the selenium-webdriver , for example:
var webdriver = require('selenium-webdriver'); var fs = require('fs'); var resumer = require('resumer'); webdriver.WebDriver.prototype.saveScreenshot = function(filename) { return this.takeScreenshot().then(function(data) { fs.writeFile(filename, data.replace(/^data:image\/png;base64,/,''), 'base64', function(err) { if(err) throw err; }); }); }; webdriver.WebDriver.prototype.streamScreenshot = function() { var stream = resumer(); this.takeScreenshot().then(function(data) { stream.queue(new Buffer(data.replace(/^data:image\/png;base64,/,''), 'base64')).end(); }); return stream; }; module.exports = webdriver;
And then I just turn on my advanced web editor instead of the official one:
var webdriver = require('./webdriver.ext');
I think the correct way to extend objects in Node JS.
Problem
The problem I am facing is adding a custom locator strategy. Strategies are as follows:
/** * Factory methods for the supported locator strategies. * @type {Object.<function(string):!webdriver.Locator>} */ webdriver.Locator.Strategy = { 'className': webdriver.Locator.factory_('class name'), 'class name': webdriver.Locator.factory_('class name'), 'css': webdriver.Locator.factory_('css selector'), 'id': webdriver.Locator.factory_('id'), 'js': webdriver.Locator.factory_('js'), 'linkText': webdriver.Locator.factory_('link text'), 'link text': webdriver.Locator.factory_('link text'), 'name': webdriver.Locator.factory_('name'), 'partialLinkText': webdriver.Locator.factory_('partial link text'), 'partial link text': webdriver.Locator.factory_('partial link text'), 'tagName': webdriver.Locator.factory_('tag name'), 'tag name': webdriver.Locator.factory_('tag name'), 'xpath': webdriver.Locator.factory_('xpath') }; goog.exportSymbol('By', webdriver.Locator.Strategy);
I am trying to add a new one by injecting it into this object:
webdriver.By.sizzle = function(selector) { driver.executeScript("return typeof Sizzle==='undefined'").then(function(noSizzle) { if(noSizzle) driver.executeScript(fs.readFileSync('sizzle.min.js', {encoding: 'utf8'})); }); return new webdriver.By.js("return Sizzle("+JSON.stringify(selector)+")[0]"); };
This is really great for simple scripts where driver defined (note that I am using a global variable).
Is there a way to access the "current driver" inside my function? In contrast to the methods above, this is not the prototype method, so I do not have access to this .
I do not know how those factory_ work; I just guessed that I could directly enter the function.