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