Driver.pm 72 KB

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