1
0

Driver.pm 64 KB

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