1
0

Driver.pm 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  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 be
  1130. specified by its server assigned window handle, or by the value of its name
  1131. attribute.
  1132. Input: 1
  1133. Required:
  1134. STRING - Window handle or the Window name
  1135. Usage:
  1136. $driver->switch_to_window('MY Homepage');
  1137. or
  1138. # close a popup window and switch back
  1139. my $handles = $driver->get_window_handles;
  1140. $driver->switch_to_window($handles->[1]);
  1141. $driver->close;
  1142. $driver->switch_to_window($handles->[0]);
  1143. =cut
  1144. sub switch_to_window {
  1145. my ( $self, $name ) = @_;
  1146. if ( not defined $name ) {
  1147. return 'Window name not provided';
  1148. }
  1149. my $res = { 'command' => 'switchToWindow' };
  1150. my $params = { 'name' => $name };
  1151. return $self->_execute_command( $res, $params );
  1152. }
  1153. =head2 get_speed
  1154. Description:
  1155. Get the current user input speed. The actual input speed is still browser
  1156. specific and not covered by the Driver.
  1157. Output:
  1158. STRING - One of these: SLOW, MEDIUM, FAST
  1159. Usage:
  1160. print $driver->get_speed();
  1161. =cut
  1162. sub get_speed {
  1163. my ($self) = @_;
  1164. my $res = { 'command' => 'getSpeed' };
  1165. return $self->_execute_command($res);
  1166. }
  1167. =head2 set_speed
  1168. Description:
  1169. Set the user input speed.
  1170. Input:
  1171. STRING - One of these: SLOW, MEDIUM, FAST
  1172. Usage:
  1173. $driver->set_speed('MEDIUM');
  1174. Note: This function is a no-op in WebDriver (?). See
  1175. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion and
  1176. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  1177. =cut
  1178. sub set_speed {
  1179. my ( $self, $speed ) = @_;
  1180. if ( not defined $speed ) {
  1181. return 'Speed not provided.';
  1182. }
  1183. my $res = { 'command' => 'setSpeed' };
  1184. my $params = { 'speed' => $speed };
  1185. return $self->_execute_command( $res, $params );
  1186. }
  1187. =head2 set_window_position
  1188. Description:
  1189. Set the position (on screen) where you want your browser to be displayed.
  1190. Input:
  1191. INT - x co-ordinate
  1192. INT - y co-ordinate
  1193. STRING - <optional> - window handle (default is 'current' window)
  1194. Output:
  1195. BOOLEAN - Success or failure
  1196. Usage:
  1197. $driver->set_window_position(50, 50);
  1198. =cut
  1199. sub set_window_position {
  1200. my ( $self, $x, $y, $window ) = @_;
  1201. $window = ( defined $window ) ? $window : 'current';
  1202. if ( not defined $x and not defined $y ) {
  1203. croak "X & Y co-ordinates are required";
  1204. }
  1205. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1206. my $params = { 'x' => $x, 'y' => $y };
  1207. my $ret = $self->_execute_command( $res, $params );
  1208. return $ret ? 1 : 0;
  1209. }
  1210. =head2 set_window_size
  1211. Description:
  1212. Set the size of the browser window
  1213. Input:
  1214. INT - height of the window
  1215. INT - width of the window
  1216. STRING - <optional> - window handle (default is 'current' window)
  1217. Output:
  1218. BOOLEAN - Success or failure
  1219. Usage:
  1220. $driver->set_window_size(640, 480);
  1221. =cut
  1222. sub set_window_size {
  1223. my ( $self, $height, $width, $window ) = @_;
  1224. $window = ( defined $window ) ? $window : 'current';
  1225. if ( not defined $height and not defined $width ) {
  1226. croak "height & width of browser are required";
  1227. }
  1228. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1229. my $params = { 'height' => $height, 'width' => $width };
  1230. my $ret = $self->_execute_command( $res, $params );
  1231. return $ret ? 1 : 0;
  1232. }
  1233. =head2 get_all_cookies
  1234. Description:
  1235. Retrieve all cookies visible to the current page. Each cookie will be
  1236. returned as a HASH reference with the following keys & their value types:
  1237. 'name' - STRING
  1238. 'value' - STRING
  1239. 'path' - STRING
  1240. 'domain' - STRING
  1241. 'secure' - BOOLEAN
  1242. Output:
  1243. ARRAY of HASHES - list of all the cookie hashes
  1244. Usage:
  1245. print Dumper($driver->get_all_cookies());
  1246. =cut
  1247. sub get_all_cookies {
  1248. my ($self) = @_;
  1249. my $res = { 'command' => 'getAllCookies' };
  1250. return $self->_execute_command($res);
  1251. }
  1252. =head2 add_cookie
  1253. Description:
  1254. Set a cookie on the domain.
  1255. Input: 5 (1 optional)
  1256. Required:
  1257. 'name' - STRING
  1258. 'value' - STRING
  1259. 'path' - STRING
  1260. 'domain' - STRING
  1261. Optional:
  1262. 'secure' - BOOLEAN - default is false.
  1263. Usage:
  1264. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  1265. =cut
  1266. sub add_cookie {
  1267. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  1268. if ( ( not defined $name )
  1269. || ( not defined $value )
  1270. || ( not defined $path )
  1271. || ( not defined $domain ) )
  1272. {
  1273. croak "Missing parameters";
  1274. }
  1275. my $res = { 'command' => 'addCookie' };
  1276. my $json_false = JSON::false;
  1277. my $json_true = JSON::true;
  1278. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1279. my $params = {
  1280. 'cookie' => {
  1281. 'name' => $name,
  1282. 'value' => $value,
  1283. 'path' => $path,
  1284. 'domain' => $domain,
  1285. 'secure' => $secure,
  1286. }
  1287. };
  1288. return $self->_execute_command( $res, $params );
  1289. }
  1290. =head2 delete_all_cookies
  1291. Description:
  1292. Delete all cookies visible to the current page.
  1293. Usage:
  1294. $driver->delete_all_cookies();
  1295. =cut
  1296. sub delete_all_cookies {
  1297. my ($self) = @_;
  1298. my $res = { 'command' => 'deleteAllCookies' };
  1299. return $self->_execute_command($res);
  1300. }
  1301. =head2 delete_cookie_named
  1302. Description:
  1303. Delete the cookie with the given name. This command will be a no-op if there
  1304. is no such cookie visible to the current page.
  1305. Input: 1
  1306. Required:
  1307. STRING - name of cookie to delete
  1308. Usage:
  1309. $driver->delete_cookie_named('foo');
  1310. =cut
  1311. sub delete_cookie_named {
  1312. my ( $self, $cookie_name ) = @_;
  1313. if ( not defined $cookie_name ) {
  1314. croak "Cookie name not provided";
  1315. }
  1316. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1317. return $self->_execute_command($res);
  1318. }
  1319. =head2 get_page_source
  1320. Description:
  1321. Get the current page source.
  1322. Output:
  1323. STRING - The page source.
  1324. Usage:
  1325. print $driver->get_page_source();
  1326. =cut
  1327. sub get_page_source {
  1328. my ($self) = @_;
  1329. my $res = { 'command' => 'getPageSource' };
  1330. return $self->_execute_command($res);
  1331. }
  1332. =head2 find_element
  1333. Description:
  1334. Search for an element on the page, starting from the document root. The
  1335. located element will be returned as a WebElement object.
  1336. Input: 2 (1 optional)
  1337. Required:
  1338. STRING - The search target.
  1339. Optional:
  1340. STRING - Locator scheme to use to search the element, available schemes:
  1341. {class, class_name, css, id, link, link_text, partial_link_text,
  1342. tag_name, name, xpath}
  1343. Defaults to 'xpath' if not configured global during instantiation.
  1344. Output:
  1345. Selenium::Remote::WebElement - WebElement Object
  1346. (This could be a subclass of L<Selenium::Remote::WebElement> if C<webelement_class> was set.
  1347. Usage:
  1348. $driver->find_element("//input[\@name='q']");
  1349. =cut
  1350. sub find_element {
  1351. my ( $self, $query, $method ) = @_;
  1352. if ( not defined $query ) {
  1353. croak 'Search string to find element not provided.';
  1354. }
  1355. my $using =
  1356. ( defined $method ) ? FINDERS->{$method} : $self->default_finder;
  1357. if ( defined $using ) {
  1358. my $res = { 'command' => 'findElement' };
  1359. my $params = { 'using' => $using, 'value' => $query };
  1360. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1361. if ($@) {
  1362. if ( $@
  1363. =~ /(An element could not be located on the page using the given search parameters)/
  1364. )
  1365. {
  1366. # give details on what element wasn't found
  1367. $@ = "$1: $query,$using";
  1368. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1369. croak $@;
  1370. }
  1371. else {
  1372. # re throw if the exception wasn't what we expected
  1373. die $@;
  1374. }
  1375. }
  1376. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1377. driver => $self );
  1378. }
  1379. else {
  1380. croak "Bad method, expected - class, class_name, css, id, link,
  1381. link_text, partial_link_text, name, tag_name, xpath";
  1382. }
  1383. }
  1384. =head2 find_elements
  1385. Description:
  1386. Search for multiple elements on the page, starting from the document root.
  1387. The located elements will be returned as an array of WebElement object.
  1388. Input: 2 (1 optional)
  1389. Required:
  1390. STRING - The search target.
  1391. Optional:
  1392. STRING - Locator scheme to use to search the element, available schemes:
  1393. {class, class_name, css, id, link, link_text, partial_link_text,
  1394. tag_name, name, xpath}
  1395. Defaults to 'xpath' if not configured global during instantiation.
  1396. Output:
  1397. ARRAY or ARRAYREF of WebElement Objects
  1398. Usage:
  1399. $driver->find_elements("//input");
  1400. =cut
  1401. sub find_elements {
  1402. my ( $self, $query, $method ) = @_;
  1403. if ( not defined $query ) {
  1404. croak 'Search string to find element not provided.';
  1405. }
  1406. my $using =
  1407. ( defined $method ) ? FINDERS->{$method} : $self->default_finder;
  1408. if ( defined $using ) {
  1409. my $res = { 'command' => 'findElements' };
  1410. my $params = { 'using' => $using, 'value' => $query };
  1411. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1412. if ($@) {
  1413. if ( $@
  1414. =~ /(An element could not be located on the page using the given search parameters)/
  1415. )
  1416. {
  1417. # give details on what element wasn't found
  1418. $@ = "$1: $query,$using";
  1419. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1420. croak $@;
  1421. }
  1422. else {
  1423. # re throw if the exception wasn't what we expected
  1424. die $@;
  1425. }
  1426. }
  1427. my $elem_obj_arr = [];
  1428. foreach (@$ret_data) {
  1429. push(
  1430. @$elem_obj_arr,
  1431. $self->webelement_class->new(
  1432. id => $_->{ELEMENT}, driver => $self
  1433. )
  1434. );
  1435. }
  1436. return wantarray? @{$elem_obj_arr} : $elem_obj_arr ;
  1437. }
  1438. else {
  1439. croak "Bad method, expected - class, class_name, css, id, link,
  1440. link_text, partial_link_text, name, tag_name, xpath";
  1441. }
  1442. }
  1443. =head2 find_child_element
  1444. Description:
  1445. Search for an element on the page, starting from the identified element. The
  1446. located element will be returned as a WebElement object.
  1447. Input: 3 (1 optional)
  1448. Required:
  1449. Selenium::Remote::WebElement - WebElement object from where you want to
  1450. start searching.
  1451. STRING - The search target. (Do not use a double whack('//')
  1452. in an xpath to search for a child element
  1453. ex: '//option[@id="something"]'
  1454. instead use a dot whack ('./')
  1455. ex: './option[@id="something"]')
  1456. Optional:
  1457. STRING - Locator scheme to use to search the element, available schemes:
  1458. {class, class_name, css, id, link, link_text, partial_link_text,
  1459. tag_name, name, xpath}
  1460. Defaults to 'xpath' if not configured global during instantiation.
  1461. Output:
  1462. WebElement Object
  1463. Usage:
  1464. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1465. # note the usage of ./ when searching for a child element instead of //
  1466. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1467. =cut
  1468. sub find_child_element {
  1469. my ( $self, $elem, $query, $method ) = @_;
  1470. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1471. croak "Missing parameters";
  1472. }
  1473. my $using = ( defined $method ) ? $method : $self->default_finder;
  1474. if ( exists FINDERS->{$using} ) {
  1475. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1476. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1477. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1478. if ($@) {
  1479. if ( $@
  1480. =~ /(An element could not be located on the page using the given search parameters)/
  1481. )
  1482. {
  1483. # give details on what element wasn't found
  1484. $@ = "$1: $query,$using";
  1485. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1486. croak $@;
  1487. }
  1488. else {
  1489. # re throw if the exception wasn't what we expected
  1490. die $@;
  1491. }
  1492. }
  1493. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1494. driver => $self );
  1495. }
  1496. else {
  1497. croak "Bad method, expected - class, class_name, css, id, link,
  1498. link_text, partial_link_text, name, tag_name, xpath";
  1499. }
  1500. }
  1501. =head2 find_child_elements
  1502. Description:
  1503. Search for multiple element on the page, starting from the identified
  1504. element. The located elements will be returned as an array of WebElement
  1505. objects.
  1506. Input: 3 (1 optional)
  1507. Required:
  1508. Selenium::Remote::WebElement - WebElement object from where you want to
  1509. start searching.
  1510. STRING - The search target.
  1511. Optional:
  1512. STRING - Locator scheme to use to search the element, available schemes:
  1513. {class, class_name, css, id, link, link_text, partial_link_text,
  1514. tag_name, name, xpath}
  1515. Defaults to 'xpath' if not configured global during instantiation.
  1516. Output:
  1517. ARRAY of WebElement Objects.
  1518. Usage:
  1519. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1520. my $child = $driver->find_child_elements($elem1, "//option");
  1521. =cut
  1522. sub find_child_elements {
  1523. my ( $self, $elem, $query, $method ) = @_;
  1524. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1525. croak "Missing parameters";
  1526. }
  1527. my $using = ( defined $method ) ? $method : $self->default_finder;
  1528. if ( exists FINDERS->{$using} ) {
  1529. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1530. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1531. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1532. if ($@) {
  1533. if ( $@
  1534. =~ /(An element could not be located on the page using the given search parameters)/
  1535. )
  1536. {
  1537. # give details on what element wasn't found
  1538. $@ = "$1: $query,$using";
  1539. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1540. croak $@;
  1541. }
  1542. else {
  1543. # re throw if the exception wasn't what we expected
  1544. die $@;
  1545. }
  1546. }
  1547. my $elem_obj_arr = [];
  1548. my $i = 0;
  1549. foreach (@$ret_data) {
  1550. $elem_obj_arr->[$i] =
  1551. $self->webelement_class->new( id => $_->{ELEMENT},
  1552. driver => $self );
  1553. $i++;
  1554. }
  1555. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1556. }
  1557. else {
  1558. croak "Bad method, expected - class, class_name, css, id, link,
  1559. link_text, partial_link_text, name, tag_name, xpath";
  1560. }
  1561. }
  1562. =head2 get_active_element
  1563. Description:
  1564. Get the element on the page that currently has focus.. The located element
  1565. will be returned as a WebElement object.
  1566. Output:
  1567. WebElement Object
  1568. Usage:
  1569. $driver->get_active_element();
  1570. =cut
  1571. sub get_active_element {
  1572. my ($self) = @_;
  1573. my $res = { 'command' => 'getActiveElement' };
  1574. my $ret_data = eval { $self->_execute_command($res) };
  1575. if ($@) {
  1576. croak $@;
  1577. }
  1578. else {
  1579. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1580. driver => $self );
  1581. }
  1582. }
  1583. =head2 send_modifier
  1584. Description:
  1585. Send an event to the active element to depress or release a modifier key.
  1586. Input: 2
  1587. Required:
  1588. 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
  1589. isdown - Boolean/String - Whether to generate a key down or key up
  1590. Usage:
  1591. $driver->send_modifier('Alt','down');
  1592. $elem->send_keys('c');
  1593. $driver->send_modifier('Alt','up');
  1594. or
  1595. $driver->send_modifier('Alt',1);
  1596. $elem->send_keys('c');
  1597. $driver->send_modifier('Alt',0);
  1598. =cut
  1599. sub send_modifier {
  1600. my ( $self, $modifier, $isdown ) = @_;
  1601. if ( $isdown =~ /(down|up)/ ) {
  1602. $isdown = $isdown =~ /down/ ? 1 : 0;
  1603. }
  1604. my $res = { 'command' => 'sendModifier' };
  1605. my $params = {
  1606. value => $modifier,
  1607. isdown => $isdown
  1608. };
  1609. return $self->_execute_command( $res, $params );
  1610. }
  1611. =head2 compare_elements
  1612. Description:
  1613. Test if two element IDs refer to the same DOM element.
  1614. Input: 2
  1615. Required:
  1616. Selenium::Remote::WebElement - WebElement Object
  1617. Selenium::Remote::WebElement - WebElement Object
  1618. Output:
  1619. BOOLEAN
  1620. Usage:
  1621. $driver->compare_elements($elem_obj1, $elem_obj2);
  1622. =cut
  1623. sub compare_elements {
  1624. my ( $self, $elem1, $elem2 ) = @_;
  1625. my $res = {
  1626. 'command' => 'elementEquals',
  1627. 'id' => $elem1->{id},
  1628. 'other' => $elem2->{id}
  1629. };
  1630. return $self->_execute_command($res);
  1631. }
  1632. =head2 click
  1633. Description:
  1634. Click any mouse button (at the coordinates set by the last moveto command).
  1635. Input:
  1636. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  1637. defaults to 'LEFT'
  1638. Usage:
  1639. $driver->click('LEFT');
  1640. $driver->click(1); #MIDDLE
  1641. $driver->click('RIGHT');
  1642. $driver->click; #Defaults to left
  1643. =cut
  1644. sub click {
  1645. my ( $self, $button ) = @_;
  1646. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  1647. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  1648. $button = $button_enum->{ uc $1 };
  1649. }
  1650. elsif ( defined $button && $button =~ /(0|1|2)/ ) {
  1651. $button = $1;
  1652. }
  1653. else {
  1654. $button = 0;
  1655. }
  1656. my $res = { 'command' => 'click' };
  1657. my $params = { 'button' => $button };
  1658. return $self->_execute_command( $res, $params );
  1659. }
  1660. =head2 double_click
  1661. Description:
  1662. Double-clicks at the current mouse coordinates (set by moveto).
  1663. Usage:
  1664. $driver->double_click;
  1665. =cut
  1666. sub double_click {
  1667. my ($self) = @_;
  1668. my $res = { 'command' => 'doubleClick' };
  1669. return $self->_execute_command($res);
  1670. }
  1671. =head2 button_down
  1672. Description:
  1673. Click and hold the left mouse button (at the coordinates set by the
  1674. last moveto command). Note that the next mouse-related command that
  1675. should follow is buttonup . Any other mouse command (such as click
  1676. or another call to buttondown) will yield undefined behaviour.
  1677. Usage:
  1678. $self->button_down;
  1679. =cut
  1680. sub button_down {
  1681. my ($self) = @_;
  1682. my $res = { 'command' => 'buttonDown' };
  1683. return $self->_execute_command($res);
  1684. }
  1685. =head2 button_up
  1686. Description:
  1687. Releases the mouse button previously held (where the mouse is
  1688. currently at). Must be called once for every buttondown command
  1689. issued. See the note in click and buttondown about implications of
  1690. out-of-order commands.
  1691. Usage:
  1692. $self->button_up;
  1693. =cut
  1694. sub button_up {
  1695. my ($self) = @_;
  1696. my $res = { 'command' => 'buttonUp' };
  1697. return $self->_execute_command($res);
  1698. }
  1699. =head2 upload_file
  1700. Description:
  1701. Upload a file from the local machine to the selenium server
  1702. machine. That file then can be used for testing file upload on web
  1703. forms. Returns the remote-server's path to the file.
  1704. Usage:
  1705. my $remote_fname = $driver->upload_file( $fname );
  1706. my $element = $driver->find_element( '//input[@id="file"]' );
  1707. $element->send_keys( $remote_fname );
  1708. =cut
  1709. # this method duplicates upload() method in the
  1710. # org.openqa.selenium.remote.RemoteWebElement java class.
  1711. sub upload_file {
  1712. my ( $self, $filename ) = @_;
  1713. if ( not -r $filename ) { die "upload_file: no such file: $filename"; }
  1714. my $string = ""; # buffer
  1715. zip $filename => \$string
  1716. or die "zip failed: $ZipError\n"; # compress the file into string
  1717. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  1718. require MIME::Base64;
  1719. my $params = {
  1720. file => MIME::Base64::encode_base64($string) # base64-encoded string
  1721. };
  1722. return $self->_execute_command( $res, $params );
  1723. }
  1724. =head2 get_text
  1725. Description:
  1726. Get the text of a particular element. Wrapper around L<find_element()>
  1727. Usage:
  1728. $text = $driver->get_text("//div[\@name='q']");
  1729. =cut
  1730. sub get_text {
  1731. my $self = shift;
  1732. return $self->find_element(@_)->get_text();
  1733. }
  1734. =head2 get_body
  1735. Description:
  1736. Get the current text for the whole body. If you want the entire raw HTML instead,
  1737. See L<get_page_source>.
  1738. Usage:
  1739. $body_text = $driver->get_body();
  1740. =cut
  1741. sub get_body {
  1742. my $self = shift;
  1743. return $self->get_text('//body', 'xpath');
  1744. }
  1745. =head2 get_path
  1746. Description:
  1747. Get the path part of the current browser location.
  1748. Usage:
  1749. $path = $driver->get_path();
  1750. =cut
  1751. sub get_path {
  1752. my $self = shift;
  1753. my $location = $self->get_current_url;
  1754. $location =~ s/\?.*//; # strip of query params
  1755. $location =~ s/#.*//; # strip of anchors
  1756. $location =~ s#^https?://[^/]+##; # strip off host
  1757. return $location;
  1758. }
  1759. =head2 set_inner_window_size
  1760. Description:
  1761. Set the inner window size by closing the current window and
  1762. reopening the current page in a new window. This can be useful
  1763. when using browsers to mock as mobile devices.
  1764. This sub will be fired automatically if you set the
  1765. C<inner_window_size> hash key option during instantiation.
  1766. Input:
  1767. INT - height of the window
  1768. INT - width of the window
  1769. Output:
  1770. BOOLEAN - Success or failure
  1771. Usage:
  1772. $driver->set_inner_window_size(640, 480)
  1773. =cut
  1774. sub set_inner_window_size {
  1775. my $self = shift;
  1776. my $height = shift;
  1777. my $width = shift;
  1778. my $location = $self->get_current_url;
  1779. $self->execute_script('window.open("' . $location . '", "_blank")');
  1780. $self->close;
  1781. my @handles = @{ $self->get_window_handles };
  1782. $self->switch_to_window(pop @handles);
  1783. my @resize = (
  1784. 'window.innerHeight = ' . $height,
  1785. 'window.innerWidth = ' . $width,
  1786. 'return 1'
  1787. );
  1788. return $self->execute_script(join(';', @resize)) ? 1 : 0;
  1789. }
  1790. 1;
  1791. __END__
  1792. =head1 SEE ALSO
  1793. http://code.google.com/p/selenium/
  1794. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  1795. https://github.com/gempesaw/Selenium-Remote-Driver/wiki
  1796. Brownie
  1797. Wight
  1798. =cut