Driver.pm 71 KB

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