Driver.pm 71 KB

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