Driver.pm 64 KB

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