Driver.pm 69 KB

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