Driver.pm 76 KB

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