Driver.pm 61 KB

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