1
0

Driver.pm 64 KB

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