1
0

Driver.pm 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221
  1. package Selenium::Remote::Driver;
  2. # ABSTRACT: Perl Client for Selenium Remote Driver
  3. use Moo;
  4. use Try::Tiny;
  5. use 5.006;
  6. use v5.10.0; # Before 5.006, v5.10.0 would not be understood.
  7. # See http://perldoc.perl.org/5.10.0/functions/use.html#use-VERSION
  8. # and http://www.dagolden.com/index.php/369/version-numbers-should-be-boring/
  9. # for details.
  10. use Carp;
  11. our @CARP_NOT;
  12. use IO::Compress::Zip qw(zip $ZipError);
  13. use Scalar::Util;
  14. use Selenium::Remote::RemoteConnection;
  15. use Selenium::Remote::Commands;
  16. use Selenium::Remote::WebElement;
  17. use constant FINDERS => {
  18. class => 'class name',
  19. class_name => 'class name',
  20. css => 'css selector',
  21. id => 'id',
  22. link => 'link text',
  23. link_text => 'link text',
  24. name => 'name',
  25. partial_link_text => 'partial link text',
  26. tag_name => 'tag name',
  27. xpath => 'xpath',
  28. };
  29. =head1 SYNOPSIS
  30. use Selenium::Remote::Driver;
  31. my $driver = Selenium::Remote::Driver->new;
  32. $driver->get('http://www.google.com');
  33. print $driver->get_title();
  34. $driver->quit();
  35. =cut
  36. =head1 DESCRIPTION
  37. Selenium is a test tool that allows you to write
  38. automated web application UI tests in any programming language against
  39. any HTTP website using any mainstream JavaScript-enabled browser. This module is
  40. an implementation of the client for the Remote driver that Selenium provides.
  41. You can find bindings for other languages at this location:
  42. L<http://code.google.com/p/selenium/>
  43. This module sends commands directly to the Server using HTTP. Using this module
  44. together with the Selenium Server, you can automatically control any supported
  45. browser. To use this module, you need to have already downloaded and started
  46. the Selenium Server (Selenium Server is a Java application).
  47. =cut
  48. =head1 USAGE (read this first)
  49. =head2 Remote Driver Response
  50. Selenium::Remote::Driver uses the L<JsonWireProtocol|http://code.google.com/p/selenium/wiki/JsonWireProtocol> to communicate with the
  51. Selenium Server. If an error occurs while executing the command then the server
  52. sends back an HTTP error code with a JSON encoded reponse that indicates the
  53. precise L<Response Error Code|http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes>. The module will then croak with the error message
  54. associated with this code. If no error occurred, then the subroutine called will
  55. return the value sent back from the server (if a return value was sent).
  56. So a rule of thumb while invoking methods on the driver is if the method did not
  57. croak when called, then you can safely assume the command was successful even if
  58. nothing was returned by the method.
  59. =head2 WebElement
  60. Selenium Webdriver represents all the HTML elements as WebElement, which is
  61. in turn represented by L<Selenium::Remote::WebElement> module. So any method that
  62. deals with WebElements will return and/or expect WebElement object. The POD for
  63. that module describes all the methods that perform various actions on the
  64. WebElements like click, submit etc.
  65. To interact with any WebElement you have to first "find" it, read the POD for
  66. find_element or find_elements for further info. Once you find the required element
  67. then you can perform various actions. If you don't call find_* method first, all
  68. your further actions will fail for that element. Finally, just remember that you
  69. don't have to instantiate WebElement objects at all - they will be automatically
  70. created when you use the find_* methods.
  71. A sub-class of Selenium::Remote::WebElement may be used instead of Selenium::Remote::WebElement,
  72. by providing that class name as an option the constructor:
  73. my $driver = Selenium::Remote::Driver->new( webelement_class => ... );
  74. For example, a testing-subclass may extend the web-element object with testing methods.
  75. =head1 TESTING
  76. If are writing automated tests using this module, make sure you also see
  77. L<Test::Selenium::Remote::Driver> which is also included in this distribution.
  78. It includes convenience testing methods for many of the selenum methods
  79. available here.
  80. =head1 FUNCTIONS
  81. =head2 new
  82. Description:
  83. Constructor for Driver. It'll instantiate the object if it can communicate
  84. with the Selenium Webdriver server.
  85. Input: (all optional)
  86. Desired capabilities - HASH - Following options are accepted:
  87. Optional:
  88. 'remote_server_addr' - <string> - IP or FQDN of the Webdriver server machine
  89. 'port' - <string> - Port on which the Webdriver server is listening
  90. 'browser_name' - <string> - desired browser string: {phantomjs|firefox|internet explorer|htmlunit|iphone|chrome}
  91. 'version' - <string> - desired browser version number
  92. 'platform' - <string> - desired platform: {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANY}
  93. 'javascript' - <boolean> - whether javascript should be supported
  94. 'accept_ssl_certs' - <boolean> - whether SSL certs should be accepted, default is true.
  95. 'firefox_profile' - Profile - Use S::R::D::Firefox::Profile to create a Firefox profile for the browser to use
  96. 'proxy' - HASH - Proxy configuration with the following keys:
  97. 'proxyType' - <string> - REQUIRED, Possible values are:
  98. direct - A direct connection - no proxy in use,
  99. manual - Manual proxy settings configured, e.g. setting a proxy for HTTP, a proxy for FTP, etc,
  100. pac - Proxy autoconfiguration from a URL,
  101. autodetect - proxy autodetection, probably with WPAD,
  102. system - Use system settings
  103. 'proxyAutoconfigUrl' - <string> - REQUIRED if proxyType is 'pac', ignored otherwise. Expected format: http://hostname.com:1234/pacfile.
  104. 'ftpProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  105. 'httpProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  106. 'sslProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  107. 'extra_capabilities' - HASH - Any other extra capabilities
  108. You can also specify some options in the constructor hash that are
  109. not part of the browser-related desired capabilities. These items
  110. are also optional.
  111. 'auto_close' - <boolean> - whether driver should end session on remote server on close.
  112. 'default_finder' - <string> - choose default finder used for find_element* {class|class_name|css|id|link|link_text|name|partial_link_text|tag_name|xpath}
  113. 'webelement_class' - <string> - sub-class of Selenium::Remote::WebElement if you wish to use an alternate WebElement class.
  114. 'ua' - LWP::UserAgent instance - if you wish to use a specific $ua, like from Test::LWP::UserAgent
  115. If no values are provided, then these defaults will be assumed:
  116. 'remote_server_addr' => 'localhost'
  117. 'port' => '4444'
  118. 'browser_name' => 'firefox'
  119. 'version' => ''
  120. 'platform' => 'ANY'
  121. 'javascript' => 1
  122. 'auto_close' => 1
  123. 'default_finder' => 'xpath'
  124. Output:
  125. Remote Driver object
  126. Usage:
  127. my $driver = Selenium::Remote::Driver->new;
  128. or
  129. my $driver = Selenium::Remote::Driver->new('browser_name' => 'firefox',
  130. 'platform' => 'MAC');
  131. or
  132. my $driver = Selenium::Remote::Driver->new('remote_server_addr' => '10.10.1.1',
  133. 'port' => '2222',
  134. 'auto_close' => 0);
  135. or
  136. my $driver = Selenium::Remote::Driver->new('browser_name' =>'chrome'
  137. 'extra_capabilities' => {
  138. 'chromeOptions' => {
  139. 'args' => [
  140. 'window-size=1260,960',
  141. 'incognito'
  142. ],
  143. 'prefs' => {
  144. 'session' => {
  145. 'restore_on_startup' => 4,
  146. 'urls_to_restore_on_startup' => [
  147. 'http://www.google.com',
  148. 'http://docs.seleniumhq.org'
  149. ]},
  150. 'first_run_tabs' => [
  151. 'http://www.google.com',
  152. 'http://docs.seleniumhq.org'
  153. ]
  154. }
  155. }
  156. });
  157. or
  158. my $driver = Selenium::Remote::Driver->new('proxy' => {'proxyType' => 'manual', 'httpProxy' => 'myproxy.com:1234'});
  159. or
  160. my $driver = Selenium::Remote::Driver->new('default_finder' => 'css');
  161. =head2 new_from_caps
  162. Description:
  163. For experienced users who want complete control over the desired
  164. capabilities, use this alternative constructor along with the
  165. C<desired_capabilities> hash key in the init hash. Unlike "new",
  166. this constructor will not assume any defaults for your desired
  167. capabilities.
  168. This alternate constructor IGNORES all other browser-related
  169. desiredCapability options; the only options that will be respected
  170. are those that are NOT part of the Capabilities JSON Object as
  171. described in the Json Wire Protocol.
  172. Input:
  173. The only respected keys in the input hash are:
  174. remote_server_addr - STRING - defaults to localhost
  175. port - INTEGER - defaults to 4444
  176. default_finder - STRING - defaults to xpath
  177. webelement_class - STRING - defaults to Selenium::Remote::WebElement
  178. auto_close - BOOLEAN - defaults to 1
  179. desired_capabilities - HASHREF - defaults to {}
  180. Except for C<desired_capabilities>, these keys perform exactly the
  181. same as listed in the regular "new" constructor.
  182. The hashref you pass in as desired_capabilities only gets json
  183. encoded before being passed to the Selenium server; no default
  184. options of any sort will be added.
  185. This means you must handle normalization and casing of the input
  186. options (like "browser_name" vs "browserName") and take care of
  187. things like encoding the firefox profile if applicable. More
  188. information about the desired capabilities object is available on
  189. the Selenium wiki:
  190. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  191. Output:
  192. Remote Driver object
  193. Usage:
  194. my $driver = Selenium::Remote::Driver->new_from_caps(
  195. 'desired_capabilities' => {'browserName' => 'firefox'}
  196. );
  197. The above would generate a POST to the webdriver server at
  198. localhost:4444 with the exact payload of '{"desiredCapabilities":
  199. {"browserName": "firefox" }}'.
  200. =cut
  201. has 'remote_server_addr' => (
  202. is => 'rw',
  203. coerce => sub { ( defined($_[0]) ? $_[0] : 'localhost' )},
  204. default => sub {'localhost'},
  205. );
  206. has 'browser_name' => (
  207. is => 'rw',
  208. coerce => sub { ( defined($_[0]) ? $_[0] : 'firefox' )},
  209. default => sub {'firefox'},
  210. );
  211. has 'platform' => (
  212. is => 'rw',
  213. coerce => sub { ( defined($_[0]) ? $_[0] : 'ANY' )},
  214. default => sub {'ANY'},
  215. );
  216. has 'port' => (
  217. is => 'rw',
  218. coerce => sub { ( defined($_[0]) ? $_[0] : '4444' )},
  219. default => sub {'4444'},
  220. );
  221. has 'version' => (
  222. is => 'rw',
  223. default => sub {''},
  224. );
  225. has 'webelement_class' => (
  226. is => 'rw',
  227. default => sub {'Selenium::Remote::WebElement'},
  228. );
  229. has 'default_finder' => (
  230. is => 'rw',
  231. coerce => sub { FINDERS->{ $_[0] } },
  232. default => sub {'xpath'},
  233. );
  234. has 'session_id' => (
  235. is => 'rw',
  236. default => sub {undef},
  237. );
  238. has 'remote_conn' => (
  239. is => 'lazy',
  240. builder => sub {
  241. my $self = shift;
  242. return Selenium::Remote::RemoteConnection->new(
  243. remote_server_addr => $self->remote_server_addr,
  244. port => $self->port,
  245. ua => $self->ua
  246. );
  247. },
  248. );
  249. has 'ua' => (
  250. is => 'lazy',
  251. builder => sub { return LWP::UserAgent->new }
  252. );
  253. has 'commands' => (
  254. is => 'lazy',
  255. builder => sub { return Selenium::Remote::Commands->new; },
  256. );
  257. has 'auto_close' => (
  258. is => 'rw',
  259. coerce => sub { ( defined($_[0]) ? $_[0] : 1 )},
  260. default => sub {1},
  261. );
  262. has 'pid' => (
  263. is => 'lazy',
  264. builder => sub { return $$ }
  265. );
  266. has 'javascript' => (
  267. is => 'rw',
  268. coerce => sub { $_[0] ? JSON::true : JSON::false },
  269. default => sub { return JSON::true }
  270. );
  271. has 'accept_ssl_certs' => (
  272. is => 'rw',
  273. coerce => sub { $_[0] ? JSON::true : JSON::false },
  274. default => sub { return JSON::true }
  275. );
  276. has 'proxy' => (
  277. is => 'rw',
  278. coerce => sub {
  279. my $proxy = $_[0];
  280. if ( $proxy->{proxyType} eq 'pac' ) {
  281. if ( not defined $proxy->{proxyAutoconfigUrl} ) {
  282. croak "proxyAutoconfigUrl not provided\n";
  283. }
  284. elsif ( not( $proxy->{proxyAutoconfigUrl} =~ /^http/g ) ) {
  285. croak "proxyAutoconfigUrl should be of format http://";
  286. }
  287. }
  288. $proxy;
  289. },
  290. );
  291. has 'extra_capabilities' => (
  292. is => 'rw',
  293. default => sub { {} }
  294. );
  295. has 'firefox_profile' => (
  296. is => 'rw',
  297. coerce => sub {
  298. my $profile = shift;
  299. unless (Scalar::Util::blessed($profile)
  300. && $profile->isa('Selenium::Remote::Driver::Firefox::Profile')) {
  301. croak "firefox_profile should be a Selenium::Remote::Driver::Firefox::Profile\n";
  302. }
  303. return $profile->_encode;
  304. },
  305. predicate => 'has_firefox_profile'
  306. );
  307. has 'desired_capabilities' => (
  308. is => 'rw',
  309. lazy => 1,
  310. predicate => 'has_desired_capabilities'
  311. );
  312. has 'testing' => (
  313. is => 'rw',
  314. default => sub { 0 },
  315. );
  316. sub BUILD {
  317. my $self = shift;
  318. # disable server connection when testing attribute is on
  319. unless ($self->testing) {
  320. if ($self->has_desired_capabilities) {
  321. $self->new_desired_session( $self->desired_capabilities );
  322. }
  323. else {
  324. # Connect to remote server & establish a new session
  325. $self->new_session( $self->extra_capabilities );
  326. }
  327. if ( !( defined $self->session_id ) ) {
  328. croak "Could not establish a session with the remote server\n";
  329. }
  330. }
  331. }
  332. sub new_from_caps {
  333. my ($self, %args) = @_;
  334. if (not exists $args{desired_capabilities}) {
  335. $args{desired_capabilities} = {};
  336. }
  337. return $self->new(%args);
  338. }
  339. sub DEMOLISH {
  340. my ($self) = @_;
  341. return if $$ != $self->pid;
  342. $self->quit() if ( $self->auto_close && defined $self->session_id );
  343. }
  344. # This is an internal method used the Driver & is not supposed to be used by
  345. # end user. This method is used by Driver to set up all the parameters
  346. # (url & JSON), send commands & receive processed response from the server.
  347. sub _execute_command {
  348. my ( $self, $res, $params ) = @_;
  349. $res->{'session_id'} = $self->session_id;
  350. my $resource = $self->commands->get_params($res);
  351. if ($resource) {
  352. my $resp =
  353. $self->remote_conn->request( $resource->{'method'},
  354. $resource->{'url'}, $params );
  355. if ( ref($resp) eq 'HASH' ) {
  356. if ( $resp->{cmd_status} && $resp->{cmd_status} eq 'OK' ) {
  357. return $resp->{cmd_return};
  358. }
  359. else {
  360. my $msg = "Error while executing command";
  361. if ( $resp->{cmd_error} ) {
  362. $msg .= ": $resp->{cmd_error}" if $resp->{cmd_error};
  363. }
  364. elsif ( $resp->{cmd_return} ) {
  365. if ( ref( $resp->{cmd_return} ) eq 'HASH' ) {
  366. $msg .= ": $resp->{cmd_return}->{error}->{msg}"
  367. if $resp->{cmd_return}->{error}->{msg};
  368. $msg .= ": $resp->{cmd_return}->{message}"
  369. if $resp->{cmd_return}->{message};
  370. }
  371. else {
  372. $msg .= ": $resp->{cmd_return}";
  373. }
  374. }
  375. croak $msg;
  376. }
  377. }
  378. return $resp;
  379. }
  380. else {
  381. croak "Couldn't retrieve command settings properly\n";
  382. }
  383. }
  384. # A method that is used by the Driver itself. It'll be called to set the
  385. # desired capabilities on the server.
  386. sub new_session {
  387. my ( $self, $extra_capabilities ) = @_;
  388. $extra_capabilities ||= {};
  389. my $args = {
  390. 'desiredCapabilities' => {
  391. 'browserName' => $self->browser_name,
  392. 'platform' => $self->platform,
  393. 'javascriptEnabled' => $self->javascript,
  394. 'version' => $self->version,
  395. 'acceptSslCerts' => $self->accept_ssl_certs,
  396. %$extra_capabilities,
  397. },
  398. };
  399. if ( defined $self->proxy ) {
  400. $args->{desiredCapabilities}->{proxy} = $self->proxy;
  401. }
  402. if ($args->{desiredCapabilities}->{browserName} =~ /firefox/i
  403. && $self->has_firefox_profile) {
  404. $args->{desiredCapabilities}->{firefox_profile} = $self->firefox_profile;
  405. }
  406. $self->_request_new_session($args);
  407. }
  408. sub new_desired_session {
  409. my ( $self, $caps ) = @_;
  410. $self->_request_new_session({
  411. desiredCapabilities => $caps
  412. });
  413. }
  414. sub _request_new_session {
  415. my ( $self, $args ) = @_;
  416. # command => 'newSession' to fool the tests of commands implemented
  417. # TODO: rewrite the testing better, this is so fragile.
  418. my $resp = $self->remote_conn->request(
  419. $self->commands->get_method('newSession'),
  420. $self->commands->get_url('newSession'), $args,
  421. );
  422. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  423. $self->session_id( $resp->{'sessionId'} );
  424. }
  425. else {
  426. my $error = 'Could not create new session';
  427. $error .= ": $resp->{cmd_return}" if defined $resp->{cmd_return};
  428. croak $error;
  429. }
  430. }
  431. =head2 debug_on
  432. Description:
  433. Turns on debugging mode and the driver will print extra info like request
  434. and response to stdout. Useful, when you want to see what is being sent to
  435. the server & what response you are getting back.
  436. Usage:
  437. $driver->debug_on;
  438. =cut
  439. sub debug_on {
  440. my ($self) = @_;
  441. $self->remote_conn->debug(1);
  442. }
  443. =head2 debug_off
  444. Description:
  445. Turns off the debugging mode.
  446. Usage:
  447. $driver->debug_off;
  448. =cut
  449. sub debug_off {
  450. my ($self) = @_;
  451. $self->remote_conn->debug(0);
  452. }
  453. =head2 get_sessions
  454. Description:
  455. Returns a list of the currently active sessions. Each session will be
  456. returned as an array of Hashes with the following keys:
  457. 'id' : The session ID
  458. 'capabilities: An object describing session's capabilities
  459. Output:
  460. Array of Hashes
  461. Usage:
  462. print Dumper $driver->get_sessions();
  463. =cut
  464. sub get_sessions {
  465. my ($self) = @_;
  466. my $res = { 'command' => 'getSessions' };
  467. return $self->_execute_command($res);
  468. }
  469. =head2 status
  470. Description:
  471. Query the server's current status. All server implementations
  472. should return two basic objects describing the server's current
  473. platform and when the server was built.
  474. Output:
  475. Hash ref
  476. Usage:
  477. print Dumper $driver->status;
  478. =cut
  479. sub status {
  480. my ($self) = @_;
  481. my $res = { 'command' => 'status' };
  482. return $self->_execute_command($res);
  483. }
  484. =head2 get_alert_text
  485. Description:
  486. Gets the text of the currently displayed JavaScript alert(), confirm()
  487. or prompt() dialog.
  488. Example
  489. my $string = $driver->get_alert_text;
  490. =cut
  491. sub get_alert_text {
  492. my ($self) = @_;
  493. my $res = { 'command' => 'getAlertText' };
  494. return $self->_execute_command($res);
  495. }
  496. =head2 send_keys_to_active_element
  497. Description:
  498. Send a sequence of key strokes to the active element. This command is
  499. similar to the send keys command in every aspect except the implicit
  500. termination: The modifiers are not released at the end of the call.
  501. Rather, the state of the modifier keys is kept between calls, so mouse
  502. interactions can be performed while modifier keys are depressed.
  503. Input: 1
  504. Required:
  505. {ARRAY | STRING} - Array of strings or a string.
  506. Usage:
  507. $driver->send_keys_to_active_element('abcd', 'efg');
  508. $driver->send_keys_to_active_element('hijk');
  509. or
  510. # include the WDKeys module
  511. use Selenium::Remote::WDKeys;
  512. .
  513. .
  514. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  515. =cut
  516. sub send_keys_to_active_element {
  517. my ( $self, @strings ) = @_;
  518. my $res = { 'command' => 'sendKeysToActiveElement' };
  519. my $params = {
  520. 'value' => \@strings,
  521. };
  522. return $self->_execute_command( $res, $params );
  523. }
  524. =head2 send_keys_to_alert
  525. Synonymous with send_keys_to_prompt
  526. =cut
  527. sub send_keys_to_alert {
  528. return shift->send_keys_to_prompt(@_);
  529. }
  530. =head2 send_keys_to_prompt
  531. Description:
  532. Sends keystrokes to a JavaScript prompt() dialog.
  533. Input:
  534. {string} keys to send
  535. Example:
  536. $driver->send_keys_to_prompt('hello world');
  537. or
  538. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  539. $driver->send_keys_to_alert("Larry Wall");
  540. $driver->accept_alert;
  541. =cut
  542. sub send_keys_to_prompt {
  543. my ( $self, $keys ) = @_;
  544. my $res = { 'command' => 'sendKeysToPrompt' };
  545. my $params = { 'text' => $keys };
  546. return $self->_execute_command( $res, $params );
  547. }
  548. =head2 accept_alert
  549. Description:
  550. Accepts the currently displayed alert dialog. Usually, this is
  551. equivalent to clicking the 'OK' button in the dialog.
  552. Example:
  553. $driver->accept_alert;
  554. =cut
  555. sub accept_alert {
  556. my ($self) = @_;
  557. my $res = { 'command' => 'acceptAlert' };
  558. return $self->_execute_command($res);
  559. }
  560. =head2 dismiss_alert
  561. Description:
  562. Dismisses the currently displayed alert dialog. For comfirm()
  563. and prompt() dialogs, this is equivalent to clicking the
  564. 'Cancel' button. For alert() dialogs, this is equivalent to
  565. clicking the 'OK' button.
  566. Example:
  567. $driver->dismiss_alert;
  568. =cut
  569. sub dismiss_alert {
  570. my ($self) = @_;
  571. my $res = { 'command' => 'dismissAlert' };
  572. return $self->_execute_command($res);
  573. }
  574. =head2 mouse_move_to_location
  575. Description:
  576. Move the mouse by an offset of the specificed element. If no
  577. element is specified, the move is relative to the current mouse
  578. cursor. If an element is provided but no offset, the mouse will be
  579. moved to the center of the element. If the element is not visible,
  580. it will be scrolled into view.
  581. Output:
  582. STRING -
  583. Usage:
  584. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  585. # xoffset - X offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
  586. # yoffset - Y offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
  587. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  588. =cut
  589. sub mouse_move_to_location {
  590. my ( $self, %params ) = @_;
  591. $params{element} = $params{element}{id} if exists $params{element};
  592. my $res = { 'command' => 'mouseMoveToLocation' };
  593. return $self->_execute_command( $res, \%params );
  594. }
  595. =head2 move_to
  596. Synonymous with mouse_move_to_location
  597. =cut
  598. sub move_to {
  599. return shift->mouse_move_to_location(@_);
  600. }
  601. =head2 get_capabilities
  602. Description:
  603. Retrieve the capabilities of the specified session.
  604. Output:
  605. HASH of all the capabilities.
  606. Usage:
  607. my $capab = $driver->get_capabilities();
  608. print Dumper($capab);
  609. =cut
  610. sub get_capabilities {
  611. my $self = shift;
  612. my $res = { 'command' => 'getCapabilities' };
  613. return $self->_execute_command($res);
  614. }
  615. =head2 set_timeout
  616. Description:
  617. Configure the amount of time that a particular type of operation can execute
  618. for before they are aborted and a |Timeout| error is returned to the client.
  619. Input:
  620. type - <STRING> - The type of operation to set the timeout for.
  621. Valid values are:
  622. "script" : for script timeouts,
  623. "implicit" : for modifying the implicit wait timeout
  624. "page load" : for setting a page load timeout.
  625. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  626. commands are permitted to run.
  627. Usage:
  628. $driver->set_timeout('script', 1000);
  629. =cut
  630. sub set_timeout {
  631. my ( $self, $type, $ms ) = @_;
  632. if ( not defined $type or not defined $ms ) {
  633. croak "Expecting type & timeout in ms";
  634. }
  635. my $res = { 'command' => 'setTimeout' };
  636. my $params = { 'type' => $type, 'ms' => $ms };
  637. return $self->_execute_command( $res, $params );
  638. }
  639. =head2 set_async_script_timeout
  640. Description:
  641. Set the amount of time, in milliseconds, that asynchronous scripts executed
  642. by execute_async_script() are permitted to run before they are
  643. aborted and a |Timeout| error is returned to the client.
  644. Input:
  645. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  646. commands are permitted to run.
  647. Usage:
  648. $driver->set_async_script_timeout(1000);
  649. =cut
  650. sub set_async_script_timeout {
  651. my ( $self, $ms ) = @_;
  652. if ( not defined $ms ) {
  653. croak "Expecting timeout in ms";
  654. }
  655. my $res = { 'command' => 'setAsyncScriptTimeout' };
  656. my $params = { 'ms' => $ms };
  657. return $self->_execute_command( $res, $params );
  658. }
  659. =head2 set_implicit_wait_timeout
  660. Description:
  661. Set the amount of time the driver should wait when searching for elements.
  662. When searching for a single element, the driver will poll the page until
  663. an element is found or the timeout expires, whichever occurs first.
  664. When searching for multiple elements, the driver should poll the page until
  665. at least one element is found or the timeout expires, at which point it
  666. will return an empty list. If this method is never called, the driver will
  667. default to an implicit wait of 0ms.
  668. Input:
  669. Time in milliseconds.
  670. Output:
  671. Server Response Hash with no data returned back from the server.
  672. Usage:
  673. $driver->set_implicit_wait_timeout(10);
  674. =cut
  675. sub set_implicit_wait_timeout {
  676. my ( $self, $ms ) = @_;
  677. my $res = { 'command' => 'setImplicitWaitTimeout' };
  678. my $params = { 'ms' => $ms };
  679. return $self->_execute_command( $res, $params );
  680. }
  681. =head2 pause
  682. Description:
  683. Pause execution for a specified interval of milliseconds.
  684. Usage:
  685. $driver->pause(10000); # 10 second delay
  686. $driver->pause(); # 1 second delay default
  687. =cut
  688. sub pause {
  689. my $self = shift;
  690. my $timeout = ( shift // 1000 ) / 1000;
  691. select( undef, undef, undef, $timeout ); # Fractional-second sleep
  692. }
  693. =head2 close
  694. Description:
  695. Close the current window.
  696. Usage:
  697. $driver->close();
  698. or
  699. #close a popup window
  700. my $handles = $driver->get_window_handles;
  701. $driver->switch_to_window($handles->[1]);
  702. $driver->close();
  703. $driver->switch_to_window($handles->[0]);
  704. =cut
  705. sub close {
  706. my $self = shift;
  707. my $res = { 'command' => 'close' };
  708. $self->_execute_command($res);
  709. }
  710. =head2 quit
  711. Description:
  712. Delete the session & close open browsers.
  713. Usage:
  714. $driver->quit();
  715. =cut
  716. sub quit {
  717. my $self = shift;
  718. my $res = { 'command' => 'quit' };
  719. $self->_execute_command($res);
  720. $self->session_id(undef);
  721. }
  722. =head2 get_current_window_handle
  723. Description:
  724. Retrieve the current window handle.
  725. Output:
  726. STRING - the window handle
  727. Usage:
  728. print $driver->get_current_window_handle();
  729. =cut
  730. sub get_current_window_handle {
  731. my $self = shift;
  732. my $res = { 'command' => 'getCurrentWindowHandle' };
  733. return $self->_execute_command($res);
  734. }
  735. =head2 get_window_handles
  736. Description:
  737. Retrieve the list of window handles used in the session.
  738. Output:
  739. ARRAY of STRING - list of the window handles
  740. Usage:
  741. print Dumper $driver->get_window_handles;
  742. or
  743. # get popup, close, then back
  744. my $handles = $driver->get_window_handles;
  745. $driver->switch_to_window($handles->[1]);
  746. $driver->close;
  747. $driver->switch_to_window($handles->[0]);
  748. =cut
  749. sub get_window_handles {
  750. my $self = shift;
  751. my $res = { 'command' => 'getWindowHandles' };
  752. return $self->_execute_command($res);
  753. }
  754. =head2 get_window_size
  755. Description:
  756. Retrieve the window size
  757. Input:
  758. STRING - <optional> - window handle (default is 'current' window)
  759. Output:
  760. HASH - containing keys 'height' & 'width'
  761. Usage:
  762. my $window_size = $driver->get_window_size();
  763. print $window_size->{'height'}, $window_size->('width');
  764. =cut
  765. sub get_window_size {
  766. my ( $self, $window ) = @_;
  767. $window = ( defined $window ) ? $window : 'current';
  768. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  769. return $self->_execute_command($res);
  770. }
  771. =head2 get_window_position
  772. Description:
  773. Retrieve the window position
  774. Input:
  775. STRING - <optional> - window handle (default is 'current' window)
  776. Output:
  777. HASH - containing keys 'x' & 'y'
  778. Usage:
  779. my $window_size = $driver->get_window_position();
  780. print $window_size->{'x'}, $window_size->('y');
  781. =cut
  782. sub get_window_position {
  783. my ( $self, $window ) = @_;
  784. $window = ( defined $window ) ? $window : 'current';
  785. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  786. return $self->_execute_command($res);
  787. }
  788. =head2 get_current_url
  789. Description:
  790. Retrieve the url of the current page
  791. Output:
  792. STRING - url
  793. Usage:
  794. print $driver->get_current_url();
  795. =cut
  796. sub get_current_url {
  797. my $self = shift;
  798. my $res = { 'command' => 'getCurrentUrl' };
  799. return $self->_execute_command($res);
  800. }
  801. =head2 navigate
  802. Description:
  803. Navigate to a given url. This is same as get() method.
  804. Input:
  805. STRING - url
  806. Usage:
  807. $driver->navigate('http://www.google.com');
  808. =cut
  809. sub navigate {
  810. my ( $self, $url ) = @_;
  811. $self->get($url);
  812. }
  813. =head2 get
  814. Description:
  815. Navigate to a given url
  816. Input:
  817. STRING - url
  818. Usage:
  819. $driver->get('http://www.google.com');
  820. =cut
  821. sub get {
  822. my ( $self, $url ) = @_;
  823. my $res = { 'command' => 'get' };
  824. my $params = { 'url' => $url };
  825. return $self->_execute_command( $res, $params );
  826. }
  827. =head2 get_title
  828. Description:
  829. Get the current page title
  830. Output:
  831. STRING - Page title
  832. Usage:
  833. print $driver->get_title();
  834. =cut
  835. sub get_title {
  836. my $self = shift;
  837. my $res = { 'command' => 'getTitle' };
  838. return $self->_execute_command($res);
  839. }
  840. =head2 go_back
  841. Description:
  842. Equivalent to hitting the back button on the browser.
  843. Usage:
  844. $driver->go_back();
  845. =cut
  846. sub go_back {
  847. my $self = shift;
  848. my $res = { 'command' => 'goBack' };
  849. return $self->_execute_command($res);
  850. }
  851. =head2 go_forward
  852. Description:
  853. Equivalent to hitting the forward button on the browser.
  854. Usage:
  855. $driver->go_forward();
  856. =cut
  857. sub go_forward {
  858. my $self = shift;
  859. my $res = { 'command' => 'goForward' };
  860. return $self->_execute_command($res);
  861. }
  862. =head2 refresh
  863. Description:
  864. Reload the current page.
  865. Usage:
  866. $driver->refresh();
  867. =cut
  868. sub refresh {
  869. my $self = shift;
  870. my $res = { 'command' => 'refresh' };
  871. return $self->_execute_command($res);
  872. }
  873. =head2 javascript
  874. Description:
  875. returns true if javascript is enabled in the driver.
  876. Usage:
  877. if ($driver->has_javascript) { ...; }
  878. =cut
  879. sub has_javascript {
  880. my $self = shift;
  881. return $self->javascript == JSON::true;
  882. }
  883. =head2 execute_async_script
  884. Description:
  885. Inject a snippet of JavaScript into the page for execution in the context
  886. of the currently selected frame. The executed script is assumed to be
  887. asynchronous and must signal that is done by invoking the provided
  888. callback, which is always provided as the final argument to the function.
  889. The value to this callback will be returned to the client.
  890. Asynchronous script commands may not span page loads. If an unload event
  891. is fired while waiting for a script result, an error should be returned
  892. to the client.
  893. Input: 2 (1 optional)
  894. Required:
  895. STRING - Javascript to execute on the page
  896. Optional:
  897. ARRAY - list of arguments that need to be passed to the script.
  898. Output:
  899. {*} - Varied, depending on the type of result expected back from the script.
  900. Usage:
  901. my $script = q{
  902. var arg1 = arguments[0];
  903. var callback = arguments[arguments.length-1];
  904. var elem = window.document.findElementById(arg1);
  905. callback(elem);
  906. };
  907. my $elem = $driver->execute_async_script($script,'myid');
  908. $elem->click;
  909. =cut
  910. sub execute_async_script {
  911. my ( $self, $script, @args ) = @_;
  912. if ( $self->has_javascript ) {
  913. if ( not defined $script ) {
  914. croak 'No script provided';
  915. }
  916. my $res = { 'command' => 'executeAsyncScript' };
  917. # Check the args array if the elem obj is provided & replace it with
  918. # JSON representation
  919. for ( my $i = 0; $i < @args; $i++ ) {
  920. if ( Scalar::Util::blessed( $args[$i] )
  921. and $args[$i]->isa('Selenium::Remote::WebElement') )
  922. {
  923. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  924. }
  925. }
  926. my $params = { 'script' => $script, 'args' => \@args };
  927. my $ret = $self->_execute_command( $res, $params );
  928. # replace any ELEMENTS with WebElement
  929. if ( ref($ret)
  930. and ( ref($ret) eq 'HASH' )
  931. and exists $ret->{'ELEMENT'} )
  932. {
  933. $ret = $self->webelement_class->new( id => $ret->{ELEMENT},
  934. driver => $self );
  935. }
  936. return $ret;
  937. }
  938. else {
  939. croak 'Javascript is not enabled on remote driver instance.';
  940. }
  941. }
  942. =head2 execute_script
  943. Description:
  944. Inject a snippet of JavaScript into the page and return its result.
  945. WebElements that should be passed to the script as an argument should be
  946. specified in the arguments array as WebElement object. Likewise,
  947. any WebElements in the script result will be returned as WebElement object.
  948. Input: 2 (1 optional)
  949. Required:
  950. STRING - Javascript to execute on the page
  951. Optional:
  952. ARRAY - list of arguments that need to be passed to the script.
  953. Output:
  954. {*} - Varied, depending on the type of result expected back from the script.
  955. Usage:
  956. my $script = q{
  957. var arg1 = arguments[0];
  958. var elem = window.document.findElementById(arg1);
  959. return elem;
  960. };
  961. my $elem = $driver->execute_script($script,'myid');
  962. $elem->click;
  963. =cut
  964. sub execute_script {
  965. my ( $self, $script, @args ) = @_;
  966. if ( $self->has_javascript ) {
  967. if ( not defined $script ) {
  968. croak 'No script provided';
  969. }
  970. my $res = { 'command' => 'executeScript' };
  971. # Check the args array if the elem obj is provided & replace it with
  972. # JSON representation
  973. for ( my $i = 0; $i < @args; $i++ ) {
  974. if ( Scalar::Util::blessed( $args[$i] )
  975. and $args[$i]->isa('Selenium::Remote::WebElement') )
  976. {
  977. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  978. }
  979. }
  980. my $params = { 'script' => $script, 'args' => [@args] };
  981. my $ret = $self->_execute_command( $res, $params );
  982. return $self->_convert_to_webelement($ret);
  983. }
  984. else {
  985. croak 'Javascript is not enabled on remote driver instance.';
  986. }
  987. }
  988. # _convert_to_webelement
  989. # An internal method used to traverse a data structure
  990. # and convert any ELEMENTS with WebElements
  991. sub _convert_to_webelement {
  992. my ( $self, $ret ) = @_;
  993. if ( ref($ret) and ( ref($ret) eq 'HASH' ) ) {
  994. if ( ( keys %$ret == 1 ) and exists $ret->{'ELEMENT'} ) {
  995. # replace an ELEMENT with WebElement
  996. return $self->webelement_class->new( id => $ret->{ELEMENT},
  997. driver => $self );
  998. }
  999. my %hash;
  1000. foreach my $key ( keys %$ret ) {
  1001. $hash{$key} = $self->_convert_to_webelement( $ret->{$key} );
  1002. }
  1003. return \%hash;
  1004. }
  1005. if ( ref($ret) and ( ref($ret) eq 'ARRAY' ) ) {
  1006. my @array = map { $self->_convert_to_webelement($_) } @$ret;
  1007. return \@array;
  1008. }
  1009. return $ret;
  1010. }
  1011. =head2 screenshot
  1012. Description:
  1013. Get a screenshot of the current page as a base64 encoded image.
  1014. Output:
  1015. STRING - base64 encoded image
  1016. Usage:
  1017. print $driver->screenshot();
  1018. To conveniently write the screenshot to a file, see L<capture_screenshot()>.
  1019. =cut
  1020. sub screenshot {
  1021. my ($self) = @_;
  1022. my $res = { 'command' => 'screenshot' };
  1023. return $self->_execute_command($res);
  1024. }
  1025. =head2 capture_screenshot
  1026. Description:
  1027. Capture a screenshot and save as a PNG to provided file name.
  1028. (The method is compatible with the WWW::Selenium method fo the same name)
  1029. Output:
  1030. TRUE - (Screenshot is written to file)
  1031. Usage:
  1032. $driver->capture_screenshot($filename);
  1033. =cut
  1034. sub capture_screenshot {
  1035. my ( $self, $filename ) = @_;
  1036. croak '$filename is required' unless $filename;
  1037. require MIME::Base64;
  1038. open( my $fh, '>', $filename );
  1039. binmode $fh;
  1040. print $fh MIME::Base64::decode_base64( $self->screenshot() );
  1041. CORE::close $fh;
  1042. return 1;
  1043. }
  1044. =head2 available_engines
  1045. Description:
  1046. List all available engines on the machine. To use an engine, it has to be present in this list.
  1047. Output:
  1048. {Array.<string>} A list of available engines
  1049. Usage:
  1050. print Dumper $driver->available_engines;
  1051. =cut
  1052. sub available_engines {
  1053. my ($self) = @_;
  1054. my $res = { 'command' => 'availableEngines' };
  1055. return $self->_execute_command($res);
  1056. }
  1057. =head2 switch_to_frame
  1058. Description:
  1059. Change focus to another frame on the page. If the frame ID is null, the
  1060. server will switch to the page's default content. You can also switch to a
  1061. WebElement, for e.g. you can find an iframe using find_element & then
  1062. provide that as an input to this method. Also see e.g.
  1063. Input: 1
  1064. Required:
  1065. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  1066. mentioned.
  1067. Usage:
  1068. $driver->switch_to_frame('frame_1');
  1069. or
  1070. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  1071. =cut
  1072. sub switch_to_frame {
  1073. my ( $self, $id ) = @_;
  1074. my $json_null = JSON::null;
  1075. my $params;
  1076. $id = ( defined $id ) ? $id : $json_null;
  1077. my $res = { 'command' => 'switchToFrame' };
  1078. if ( ref $id eq $self->webelement_class ) {
  1079. $params = { 'id' => { 'ELEMENT' => $id->{'id'} } };
  1080. }
  1081. else {
  1082. $params = { 'id' => $id };
  1083. }
  1084. return $self->_execute_command( $res, $params );
  1085. }
  1086. =head2 switch_to_window
  1087. Description:
  1088. Change focus to another window. The window to change focus to may be
  1089. specified by its server assigned window handle, or by the value of its name
  1090. attribute.
  1091. Input: 1
  1092. Required:
  1093. STRING - Window handle or the Window name
  1094. Usage:
  1095. $driver->switch_to_window('MY Homepage');
  1096. or
  1097. # close a popup window and switch back
  1098. my $handles = $driver->get_window_handles;
  1099. $driver->switch_to_window($handles->[1]);
  1100. $driver->close;
  1101. $driver->switch_to_window($handles->[0]);
  1102. =cut
  1103. sub switch_to_window {
  1104. my ( $self, $name ) = @_;
  1105. if ( not defined $name ) {
  1106. return 'Window name not provided';
  1107. }
  1108. my $res = { 'command' => 'switchToWindow' };
  1109. my $params = { 'name' => $name };
  1110. return $self->_execute_command( $res, $params );
  1111. }
  1112. =head2 get_speed
  1113. Description:
  1114. Get the current user input speed. The actual input speed is still browser
  1115. specific and not covered by the Driver.
  1116. Output:
  1117. STRING - One of these: SLOW, MEDIUM, FAST
  1118. Usage:
  1119. print $driver->get_speed();
  1120. =cut
  1121. sub get_speed {
  1122. my ($self) = @_;
  1123. my $res = { 'command' => 'getSpeed' };
  1124. return $self->_execute_command($res);
  1125. }
  1126. =head2 set_speed
  1127. Description:
  1128. Set the user input speed.
  1129. Input:
  1130. STRING - One of these: SLOW, MEDIUM, FAST
  1131. Usage:
  1132. $driver->set_speed('MEDIUM');
  1133. Note: This function is a no-op in WebDriver (?). See
  1134. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion and
  1135. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  1136. =cut
  1137. sub set_speed {
  1138. my ( $self, $speed ) = @_;
  1139. if ( not defined $speed ) {
  1140. return 'Speed not provided.';
  1141. }
  1142. my $res = { 'command' => 'setSpeed' };
  1143. my $params = { 'speed' => $speed };
  1144. return $self->_execute_command( $res, $params );
  1145. }
  1146. =head2 set_window_position
  1147. Description:
  1148. Set the position (on screen) where you want your browser to be displayed.
  1149. Input:
  1150. INT - x co-ordinate
  1151. INT - y co-ordinate
  1152. STRING - <optional> - window handle (default is 'current' window)
  1153. Output:
  1154. BOOLEAN - Success or failure
  1155. Usage:
  1156. $driver->set_window_position(50, 50);
  1157. =cut
  1158. sub set_window_position {
  1159. my ( $self, $x, $y, $window ) = @_;
  1160. $window = ( defined $window ) ? $window : 'current';
  1161. if ( not defined $x and not defined $y ) {
  1162. croak "X & Y co-ordinates are required";
  1163. }
  1164. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1165. my $params = { 'x' => $x, 'y' => $y };
  1166. my $ret = $self->_execute_command( $res, $params );
  1167. if ( $ret =~ m/204/g ) {
  1168. return 1;
  1169. }
  1170. else { return 0; }
  1171. }
  1172. =head2 set_window_size
  1173. Description:
  1174. Set the size of the browser window
  1175. Input:
  1176. INT - height of the window
  1177. INT - width of the window
  1178. STRING - <optional> - window handle (default is 'current' window)
  1179. Output:
  1180. BOOLEAN - Success or failure
  1181. Usage:
  1182. $driver->set_window_size(640, 480);
  1183. =cut
  1184. sub set_window_size {
  1185. my ( $self, $height, $width, $window ) = @_;
  1186. $window = ( defined $window ) ? $window : 'current';
  1187. if ( not defined $height and not defined $width ) {
  1188. croak "height & width of browser are required";
  1189. }
  1190. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1191. my $params = { 'height' => $height, 'width' => $width };
  1192. my $ret = $self->_execute_command( $res, $params );
  1193. if ( $ret =~ m/204/g ) {
  1194. return 1;
  1195. }
  1196. else { return 0; }
  1197. }
  1198. =head2 get_all_cookies
  1199. Description:
  1200. Retrieve all cookies visible to the current page. Each cookie will be
  1201. returned as a HASH reference with the following keys & their value types:
  1202. 'name' - STRING
  1203. 'value' - STRING
  1204. 'path' - STRING
  1205. 'domain' - STRING
  1206. 'secure' - BOOLEAN
  1207. Output:
  1208. ARRAY of HASHES - list of all the cookie hashes
  1209. Usage:
  1210. print Dumper($driver->get_all_cookies());
  1211. =cut
  1212. sub get_all_cookies {
  1213. my ($self) = @_;
  1214. my $res = { 'command' => 'getAllCookies' };
  1215. return $self->_execute_command($res);
  1216. }
  1217. =head2 add_cookie
  1218. Description:
  1219. Set a cookie on the domain.
  1220. Input: 5 (1 optional)
  1221. Required:
  1222. 'name' - STRING
  1223. 'value' - STRING
  1224. 'path' - STRING
  1225. 'domain' - STRING
  1226. Optional:
  1227. 'secure' - BOOLEAN - default is false.
  1228. Usage:
  1229. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  1230. =cut
  1231. sub add_cookie {
  1232. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  1233. if ( ( not defined $name )
  1234. || ( not defined $value )
  1235. || ( not defined $path )
  1236. || ( not defined $domain ) )
  1237. {
  1238. croak "Missing parameters";
  1239. }
  1240. my $res = { 'command' => 'addCookie' };
  1241. my $json_false = JSON::false;
  1242. my $json_true = JSON::true;
  1243. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1244. my $params = {
  1245. 'cookie' => {
  1246. 'name' => $name,
  1247. 'value' => $value,
  1248. 'path' => $path,
  1249. 'domain' => $domain,
  1250. 'secure' => $secure,
  1251. }
  1252. };
  1253. return $self->_execute_command( $res, $params );
  1254. }
  1255. =head2 delete_all_cookies
  1256. Description:
  1257. Delete all cookies visible to the current page.
  1258. Usage:
  1259. $driver->delete_all_cookies();
  1260. =cut
  1261. sub delete_all_cookies {
  1262. my ($self) = @_;
  1263. my $res = { 'command' => 'deleteAllCookies' };
  1264. return $self->_execute_command($res);
  1265. }
  1266. =head2 delete_cookie_named
  1267. Description:
  1268. Delete the cookie with the given name. This command will be a no-op if there
  1269. is no such cookie visible to the current page.
  1270. Input: 1
  1271. Required:
  1272. STRING - name of cookie to delete
  1273. Usage:
  1274. $driver->delete_cookie_named('foo');
  1275. =cut
  1276. sub delete_cookie_named {
  1277. my ( $self, $cookie_name ) = @_;
  1278. if ( not defined $cookie_name ) {
  1279. croak "Cookie name not provided";
  1280. }
  1281. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1282. return $self->_execute_command($res);
  1283. }
  1284. =head2 get_page_source
  1285. Description:
  1286. Get the current page source.
  1287. Output:
  1288. STRING - The page source.
  1289. Usage:
  1290. print $driver->get_page_source();
  1291. =cut
  1292. sub get_page_source {
  1293. my ($self) = @_;
  1294. my $res = { 'command' => 'getPageSource' };
  1295. return $self->_execute_command($res);
  1296. }
  1297. =head2 find_element
  1298. Description:
  1299. Search for an element on the page, starting from the document root. The
  1300. located element will be returned as a WebElement object.
  1301. Input: 2 (1 optional)
  1302. Required:
  1303. STRING - The search target.
  1304. Optional:
  1305. STRING - Locator scheme to use to search the element, available schemes:
  1306. {class, class_name, css, id, link, link_text, partial_link_text,
  1307. tag_name, name, xpath}
  1308. Defaults to 'xpath' if not configured global during instantiation.
  1309. Output:
  1310. Selenium::Remote::WebElement - WebElement Object
  1311. (This could be a subclass of L<Selenium::Remote::WebElement> if C<webelement_class> was set.
  1312. Usage:
  1313. $driver->find_element("//input[\@name='q']");
  1314. =cut
  1315. sub find_element {
  1316. my ( $self, $query, $method ) = @_;
  1317. if ( not defined $query ) {
  1318. croak 'Search string to find element not provided.';
  1319. }
  1320. my $using =
  1321. ( defined $method ) ? FINDERS->{$method} : $self->default_finder;
  1322. if ( defined $using ) {
  1323. my $res = { 'command' => 'findElement' };
  1324. my $params = { 'using' => $using, 'value' => $query };
  1325. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1326. if ($@) {
  1327. if ( $@
  1328. =~ /(An element could not be located on the page using the given search parameters)/
  1329. )
  1330. {
  1331. # give details on what element wasn't found
  1332. $@ = "$1: $query,$using";
  1333. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1334. croak $@;
  1335. }
  1336. else {
  1337. # re throw if the exception wasn't what we expected
  1338. die $@;
  1339. }
  1340. }
  1341. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1342. driver => $self );
  1343. }
  1344. else {
  1345. croak "Bad method, expected - class, class_name, css, id, link,
  1346. link_text, partial_link_text, name, tag_name, xpath";
  1347. }
  1348. }
  1349. =head2 find_elements
  1350. Description:
  1351. Search for multiple elements on the page, starting from the document root.
  1352. The located elements will be returned as an array of WebElement object.
  1353. Input: 2 (1 optional)
  1354. Required:
  1355. STRING - The search target.
  1356. Optional:
  1357. STRING - Locator scheme to use to search the element, available schemes:
  1358. {class, class_name, css, id, link, link_text, partial_link_text,
  1359. tag_name, name, xpath}
  1360. Defaults to 'xpath' if not configured global during instantiation.
  1361. Output:
  1362. ARRAY or ARRAYREF of WebElement Objects
  1363. Usage:
  1364. $driver->find_elements("//input");
  1365. =cut
  1366. sub find_elements {
  1367. my ( $self, $query, $method ) = @_;
  1368. if ( not defined $query ) {
  1369. croak 'Search string to find element not provided.';
  1370. }
  1371. my $using =
  1372. ( defined $method ) ? FINDERS->{$method} : $self->default_finder;
  1373. if ( defined $using ) {
  1374. my $res = { 'command' => 'findElements' };
  1375. my $params = { 'using' => $using, 'value' => $query };
  1376. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1377. if ($@) {
  1378. if ( $@
  1379. =~ /(An element could not be located on the page using the given search parameters)/
  1380. )
  1381. {
  1382. # give details on what element wasn't found
  1383. $@ = "$1: $query,$using";
  1384. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1385. croak $@;
  1386. }
  1387. else {
  1388. # re throw if the exception wasn't what we expected
  1389. die $@;
  1390. }
  1391. }
  1392. my $elem_obj_arr = [];
  1393. foreach (@$ret_data) {
  1394. push(
  1395. @$elem_obj_arr,
  1396. $self->webelement_class->new(
  1397. id => $_->{ELEMENT}, driver => $self
  1398. )
  1399. );
  1400. }
  1401. return wantarray? @{$elem_obj_arr} : $elem_obj_arr ;
  1402. }
  1403. else {
  1404. croak "Bad method, expected - class, class_name, css, id, link,
  1405. link_text, partial_link_text, name, tag_name, xpath";
  1406. }
  1407. }
  1408. =head2 find_child_element
  1409. Description:
  1410. Search for an element on the page, starting from the identified element. The
  1411. located element will be returned as a WebElement object.
  1412. Input: 3 (1 optional)
  1413. Required:
  1414. Selenium::Remote::WebElement - WebElement object from where you want to
  1415. start searching.
  1416. STRING - The search target. (Do not use a double whack('//')
  1417. in an xpath to search for a child element
  1418. ex: '//option[@id="something"]'
  1419. instead use a dot whack ('./')
  1420. ex: './option[@id="something"]')
  1421. Optional:
  1422. STRING - Locator scheme to use to search the element, available schemes:
  1423. {class, class_name, css, id, link, link_text, partial_link_text,
  1424. tag_name, name, xpath}
  1425. Defaults to 'xpath' if not configured global during instantiation.
  1426. Output:
  1427. WebElement Object
  1428. Usage:
  1429. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1430. # note the usage of ./ when searching for a child element instead of //
  1431. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1432. =cut
  1433. sub find_child_element {
  1434. my ( $self, $elem, $query, $method ) = @_;
  1435. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1436. croak "Missing parameters";
  1437. }
  1438. my $using = ( defined $method ) ? $method : $self->default_finder;
  1439. if ( exists FINDERS->{$using} ) {
  1440. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1441. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1442. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1443. if ($@) {
  1444. if ( $@
  1445. =~ /(An element could not be located on the page using the given search parameters)/
  1446. )
  1447. {
  1448. # give details on what element wasn't found
  1449. $@ = "$1: $query,$using";
  1450. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1451. croak $@;
  1452. }
  1453. else {
  1454. # re throw if the exception wasn't what we expected
  1455. die $@;
  1456. }
  1457. }
  1458. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1459. driver => $self );
  1460. }
  1461. else {
  1462. croak "Bad method, expected - class, class_name, css, id, link,
  1463. link_text, partial_link_text, name, tag_name, xpath";
  1464. }
  1465. }
  1466. =head2 find_child_elements
  1467. Description:
  1468. Search for multiple element on the page, starting from the identified
  1469. element. The located elements will be returned as an array of WebElement
  1470. objects.
  1471. Input: 3 (1 optional)
  1472. Required:
  1473. Selenium::Remote::WebElement - WebElement object from where you want to
  1474. start searching.
  1475. STRING - The search target.
  1476. Optional:
  1477. STRING - Locator scheme to use to search the element, available schemes:
  1478. {class, class_name, css, id, link, link_text, partial_link_text,
  1479. tag_name, name, xpath}
  1480. Defaults to 'xpath' if not configured global during instantiation.
  1481. Output:
  1482. ARRAY of WebElement Objects.
  1483. Usage:
  1484. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1485. my $child = $driver->find_child_elements($elem1, "//option");
  1486. =cut
  1487. sub find_child_elements {
  1488. my ( $self, $elem, $query, $method ) = @_;
  1489. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1490. croak "Missing parameters";
  1491. }
  1492. my $using = ( defined $method ) ? $method : $self->default_finder;
  1493. if ( exists FINDERS->{$using} ) {
  1494. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1495. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1496. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1497. if ($@) {
  1498. if ( $@
  1499. =~ /(An element could not be located on the page using the given search parameters)/
  1500. )
  1501. {
  1502. # give details on what element wasn't found
  1503. $@ = "$1: $query,$using";
  1504. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1505. croak $@;
  1506. }
  1507. else {
  1508. # re throw if the exception wasn't what we expected
  1509. die $@;
  1510. }
  1511. }
  1512. my $elem_obj_arr;
  1513. my $i = 0;
  1514. foreach (@$ret_data) {
  1515. $elem_obj_arr->[$i] =
  1516. $self->webelement_class->new( id => $_->{ELEMENT},
  1517. driver => $self );
  1518. $i++;
  1519. }
  1520. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1521. }
  1522. else {
  1523. croak "Bad method, expected - class, class_name, css, id, link,
  1524. link_text, partial_link_text, name, tag_name, xpath";
  1525. }
  1526. }
  1527. =head2 get_active_element
  1528. Description:
  1529. Get the element on the page that currently has focus.. The located element
  1530. will be returned as a WebElement object.
  1531. Output:
  1532. WebElement Object
  1533. Usage:
  1534. $driver->get_active_element();
  1535. =cut
  1536. sub get_active_element {
  1537. my ($self) = @_;
  1538. my $res = { 'command' => 'getActiveElement' };
  1539. my $ret_data = eval { $self->_execute_command($res) };
  1540. if ($@) {
  1541. croak $@;
  1542. }
  1543. else {
  1544. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1545. driver => $self );
  1546. }
  1547. }
  1548. =head2 send_modifier
  1549. Description:
  1550. Send an event to the active element to depress or release a modifier key.
  1551. Input: 2
  1552. Required:
  1553. value - String - The modifier key event to be sent. This key must be one 'Ctrl','Shift','Alt',' or 'Command'/'Meta' as defined by the send keys command
  1554. isdown - Boolean/String - Whether to generate a key down or key up
  1555. Usage:
  1556. $driver->send_modifier('Alt','down');
  1557. $elem->send_keys('c');
  1558. $driver->send_modifier('Alt','up');
  1559. or
  1560. $driver->send_modifier('Alt',1);
  1561. $elem->send_keys('c');
  1562. $driver->send_modifier('Alt',0);
  1563. =cut
  1564. sub send_modifier {
  1565. my ( $self, $modifier, $isdown ) = @_;
  1566. if ( $isdown =~ /(down|up)/ ) {
  1567. $isdown = $isdown =~ /down/ ? 1 : 0;
  1568. }
  1569. my $res = { 'command' => 'sendModifier' };
  1570. my $params = {
  1571. value => $modifier,
  1572. isdown => $isdown
  1573. };
  1574. return $self->_execute_command( $res, $params );
  1575. }
  1576. =head2 compare_elements
  1577. Description:
  1578. Test if two element IDs refer to the same DOM element.
  1579. Input: 2
  1580. Required:
  1581. Selenium::Remote::WebElement - WebElement Object
  1582. Selenium::Remote::WebElement - WebElement Object
  1583. Output:
  1584. BOOLEAN
  1585. Usage:
  1586. $driver->compare_elements($elem_obj1, $elem_obj2);
  1587. =cut
  1588. sub compare_elements {
  1589. my ( $self, $elem1, $elem2 ) = @_;
  1590. my $res = {
  1591. 'command' => 'elementEquals',
  1592. 'id' => $elem1->{id},
  1593. 'other' => $elem2->{id}
  1594. };
  1595. return $self->_execute_command($res);
  1596. }
  1597. =head2 click
  1598. Description:
  1599. Click any mouse button (at the coordinates set by the last moveto command).
  1600. Input:
  1601. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  1602. defaults to 'LEFT'
  1603. Usage:
  1604. $driver->click('LEFT');
  1605. $driver->click(1); #MIDDLE
  1606. $driver->click('RIGHT');
  1607. $driver->click; #Defaults to left
  1608. =cut
  1609. sub click {
  1610. my ( $self, $button ) = @_;
  1611. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  1612. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  1613. $button = $button_enum->{ uc $1 };
  1614. }
  1615. elsif ( defined $button && $button =~ /(0|1|2)/ ) {
  1616. $button = $1;
  1617. }
  1618. else {
  1619. $button = 0;
  1620. }
  1621. my $res = { 'command' => 'click' };
  1622. my $params = { 'button' => $button };
  1623. return $self->_execute_command( $res, $params );
  1624. }
  1625. =head2 double_click
  1626. Description:
  1627. Double-clicks at the current mouse coordinates (set by moveto).
  1628. Usage:
  1629. $driver->double_click;
  1630. =cut
  1631. sub double_click {
  1632. my ($self) = @_;
  1633. my $res = { 'command' => 'doubleClick' };
  1634. return $self->_execute_command($res);
  1635. }
  1636. =head2 button_down
  1637. Description:
  1638. Click and hold the left mouse button (at the coordinates set by the
  1639. last moveto command). Note that the next mouse-related command that
  1640. should follow is buttonup . Any other mouse command (such as click
  1641. or another call to buttondown) will yield undefined behaviour.
  1642. Usage:
  1643. $self->button_down;
  1644. =cut
  1645. sub button_down {
  1646. my ($self) = @_;
  1647. my $res = { 'command' => 'buttonDown' };
  1648. return $self->_execute_command($res);
  1649. }
  1650. =head2 button_up
  1651. Description:
  1652. Releases the mouse button previously held (where the mouse is
  1653. currently at). Must be called once for every buttondown command
  1654. issued. See the note in click and buttondown about implications of
  1655. out-of-order commands.
  1656. Usage:
  1657. $self->button_up;
  1658. =cut
  1659. sub button_up {
  1660. my ($self) = @_;
  1661. my $res = { 'command' => 'buttonUp' };
  1662. return $self->_execute_command($res);
  1663. }
  1664. =head2 upload_file
  1665. Description:
  1666. Upload a file from the local machine to the selenium server
  1667. machine. That file then can be used for testing file upload on web
  1668. forms. Returns the remote-server's path to the file.
  1669. Usage:
  1670. my $remote_fname = $driver->upload_file( $fname );
  1671. my $element = $driver->find_element( '//input[@id="file"]' );
  1672. $element->send_keys( $remote_fname );
  1673. =cut
  1674. # this method duplicates upload() method in the
  1675. # org.openqa.selenium.remote.RemoteWebElement java class.
  1676. sub upload_file {
  1677. my ( $self, $filename ) = @_;
  1678. if ( not -r $filename ) { die "upload_file: no such file: $filename"; }
  1679. my $string = ""; # buffer
  1680. zip $filename => \$string
  1681. or die "zip failed: $ZipError\n"; # compress the file into string
  1682. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  1683. require MIME::Base64;
  1684. my $params = {
  1685. file => encode_base64($string) # base64-encoded string
  1686. };
  1687. return $self->_execute_command( $res, $params );
  1688. }
  1689. =head2 get_text
  1690. Description:
  1691. Get the text of a particular element. Wrapper around L<find_element()>
  1692. Usage:
  1693. $text = $driver->get_text("//div[\@name='q']");
  1694. =cut
  1695. sub get_text {
  1696. my $self = shift;
  1697. return $self->find_element(@_)->get_text();
  1698. }
  1699. =head2 get_body
  1700. Description:
  1701. Get the current text for the whole body. If you want the entire raw HTML instead,
  1702. See L<get_page_source>.
  1703. Usage:
  1704. $body_text = $driver->get_body();
  1705. =cut
  1706. sub get_body {
  1707. my $self = shift;
  1708. return $self->get_text('//body');
  1709. }
  1710. =head2 get_path
  1711. Description:
  1712. Get the path part of the current browser location.
  1713. Usage:
  1714. $path = $driver->get_path();
  1715. =cut
  1716. sub get_path {
  1717. my $self = shift;
  1718. my $location = $self->get_current_url;
  1719. $location =~ s/\?.*//; # strip of query params
  1720. $location =~ s/#.*//; # strip of anchors
  1721. $location =~ s#^https?://[^/]+##; # strip off host
  1722. return $location;
  1723. }
  1724. 1;
  1725. __END__
  1726. =head1 SEE ALSO
  1727. http://code.google.com/p/selenium/
  1728. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  1729. https://github.com/gempesaw/Selenium-Remote-Driver/wiki
  1730. =cut