Driver.pm 71 KB

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