v3.pm 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257
  1. package Selenium::Remote::Driver::v3;
  2. use strict;
  3. use warnings;
  4. # ABSTRACT: Perl Client for Selenium Remote Driver
  5. use Moo;
  6. use Try::Tiny;
  7. use 5.006;
  8. use v5.10.0; # Before 5.006, v5.10.0 would not be understood.
  9. # See http://perldoc.perl.org/5.10.0/functions/use.html#use-VERSION
  10. # and http://www.dagolden.com/index.php/369/version-numbers-should-be-boring/
  11. # for details.
  12. use Carp;
  13. our @CARP_NOT;
  14. use IO::String;
  15. use Archive::Zip qw( :ERROR_CODES );
  16. use Scalar::Util;
  17. use Selenium::Remote::RemoteConnection;
  18. use Selenium::Remote::Commands;
  19. use Selenium::Remote::Spec;
  20. use Selenium::Remote::WebElement;
  21. use Selenium::Remote::WDKeys;
  22. use File::Spec::Functions ();
  23. use File::Basename qw(basename);
  24. use Sub::Install ();
  25. use MIME::Base64 ();
  26. use Time::HiRes qw(usleep);
  27. use Clone qw{clone};
  28. use List::Util qw{any};
  29. use constant FINDERS => {
  30. class => 'class name',
  31. class_name => 'class name',
  32. css => 'css selector',
  33. id => 'id',
  34. link => 'link text',
  35. link_text => 'link text',
  36. name => 'name',
  37. partial_link_text => 'partial link text',
  38. tag_name => 'tag name',
  39. xpath => 'xpath',
  40. };
  41. our $FORCE_WD2 = 0;
  42. our $FORCE_WD3 = 0;
  43. our $FORCE_WD4 = 0;
  44. our %CURRENT_ACTION_CHAIN = ( actions => [] );
  45. has 'remote_server_addr' => (
  46. is => 'rw',
  47. coerce => sub { ( defined( $_[0] ) ? $_[0] : 'localhost' ) },
  48. default => sub { 'localhost' },
  49. predicate => 1
  50. );
  51. has 'browser_name' => (
  52. is => 'rw',
  53. coerce => sub { ( defined( $_[0] ) ? $_[0] : 'firefox' ) },
  54. default => sub { 'firefox' },
  55. );
  56. has 'base_url' => (
  57. is => 'lazy',
  58. coerce => sub {
  59. my $base_url = shift;
  60. $base_url =~ s|/$||;
  61. return $base_url;
  62. },
  63. predicate => 'has_base_url',
  64. );
  65. has 'platform' => (
  66. is => 'rw',
  67. coerce => sub { ( defined( $_[0] ) ? $_[0] : 'ANY' ) },
  68. default => sub { 'ANY' },
  69. );
  70. has 'port' => (
  71. is => 'rw',
  72. coerce => sub { ( defined( $_[0] ) ? $_[0] : '4444' ) },
  73. default => sub { '4444' },
  74. predicate => 1
  75. );
  76. has 'version' => (
  77. is => 'rw',
  78. default => sub { '' },
  79. );
  80. has 'webelement_class' => (
  81. is => 'rw',
  82. default => sub { 'Selenium::Remote::WebElement' },
  83. );
  84. has 'default_finder' => (
  85. is => 'rw',
  86. coerce => sub { __PACKAGE__->FINDERS->{ $_[0] } },
  87. default => sub { 'xpath' },
  88. );
  89. has 'session_id' => (
  90. is => 'rw',
  91. default => sub { undef },
  92. );
  93. has 'remote_conn' => (
  94. is => 'lazy',
  95. builder => sub {
  96. my $self = shift;
  97. return Selenium::Remote::RemoteConnection->new(
  98. remote_server_addr => $self->remote_server_addr,
  99. port => $self->port,
  100. ua => $self->ua,
  101. wd_context_prefix => $self->wd_context_prefix
  102. );
  103. },
  104. );
  105. has 'error_handler' => (
  106. is => 'rw',
  107. coerce => sub {
  108. my ($maybe_coderef) = @_;
  109. if ( ref($maybe_coderef) eq 'CODE' ) {
  110. return $maybe_coderef;
  111. }
  112. else {
  113. croak 'The error handler must be a code ref.';
  114. }
  115. },
  116. clearer => 1,
  117. predicate => 1
  118. );
  119. has 'ua' => (
  120. is => 'lazy',
  121. builder => sub { return LWP::UserAgent->new }
  122. );
  123. has 'commands' => (
  124. is => 'lazy',
  125. builder => sub {
  126. return Selenium::Remote::Commands->new;
  127. },
  128. );
  129. has 'commands_v3' => (
  130. is => 'lazy',
  131. builder => sub {
  132. return Selenium::Remote::Spec->new;
  133. },
  134. );
  135. has 'auto_close' => (
  136. is => 'rw',
  137. coerce => sub { ( defined( $_[0] ) ? $_[0] : 1 ) },
  138. default => sub { 1 },
  139. );
  140. has 'pid' => (
  141. is => 'lazy',
  142. builder => sub { return $$ }
  143. );
  144. has 'javascript' => (
  145. is => 'rw',
  146. coerce => sub { $_[0] ? JSON::true : JSON::false },
  147. default => sub { return JSON::true }
  148. );
  149. has 'accept_ssl_certs' => (
  150. is => 'rw',
  151. coerce => sub { $_[0] ? JSON::true : JSON::false },
  152. default => sub { return JSON::true }
  153. );
  154. has 'proxy' => (
  155. is => 'rw',
  156. coerce => sub {
  157. my $proxy = $_[0];
  158. if ( $proxy->{proxyType} =~ /^pac$/i ) {
  159. if ( not defined $proxy->{proxyAutoconfigUrl} ) {
  160. croak "proxyAutoconfigUrl not provided\n";
  161. }
  162. elsif ( not( $proxy->{proxyAutoconfigUrl} =~ /^(http|file)/g ) ) {
  163. croak
  164. "proxyAutoconfigUrl should be of format http:// or file://";
  165. }
  166. if ( $proxy->{proxyAutoconfigUrl} =~ /^file/ ) {
  167. my $pac_url = $proxy->{proxyAutoconfigUrl};
  168. my $file = $pac_url;
  169. $file =~ s{^file://}{};
  170. if ( !-e $file ) {
  171. warn "proxyAutoConfigUrl file does not exist: '$pac_url'";
  172. }
  173. }
  174. }
  175. $proxy;
  176. },
  177. );
  178. has 'extra_capabilities' => (
  179. is => 'rw',
  180. default => sub { {} }
  181. );
  182. has 'firefox_profile' => (
  183. is => 'rw',
  184. coerce => sub {
  185. my $profile = shift;
  186. unless ( Scalar::Util::blessed($profile)
  187. && $profile->isa('Selenium::Firefox::Profile') )
  188. {
  189. croak "firefox_profile should be a Selenium::Firefox::Profile\n";
  190. }
  191. return $profile;
  192. },
  193. predicate => 'has_firefox_profile',
  194. clearer => 1
  195. );
  196. has debug => (
  197. is => 'lazy',
  198. default => sub { 0 },
  199. );
  200. has 'desired_capabilities' => (
  201. is => 'lazy',
  202. predicate => 'has_desired_capabilities'
  203. );
  204. has 'inner_window_size' => (
  205. is => 'lazy',
  206. predicate => 1,
  207. coerce => sub {
  208. my $size = shift;
  209. croak "inner_window_size must have two elements: [ height, width ]"
  210. unless scalar @$size == 2;
  211. foreach my $dim (@$size) {
  212. croak 'inner_window_size only accepts integers, not: ' . $dim
  213. unless Scalar::Util::looks_like_number($dim);
  214. }
  215. return $size;
  216. },
  217. );
  218. # At the time of writing, Geckodriver uses a different endpoint than
  219. # the java bindings for executing synchronous and asynchronous
  220. # scripts. As a matter of fact, Geckodriver does conform to the W3C
  221. # spec, but as are bound to support both while the java bindings
  222. # transition to full spec support, we need some way to handle the
  223. # difference.
  224. has '_execute_script_suffix' => (
  225. is => 'lazy',
  226. default => ''
  227. );
  228. with 'Selenium::Remote::Finders';
  229. with 'Selenium::Remote::Driver::CanSetWebdriverContext';
  230. sub BUILD {
  231. my $self = shift;
  232. if ( !( defined $self->session_id ) ) {
  233. if ( $self->has_desired_capabilities ) {
  234. $self->new_desired_session( $self->desired_capabilities );
  235. }
  236. else {
  237. # Connect to remote server & establish a new session
  238. $self->new_session( $self->extra_capabilities );
  239. }
  240. }
  241. if ( !( defined $self->session_id ) ) {
  242. croak "Could not establish a session with the remote server\n";
  243. }
  244. elsif ( $self->has_inner_window_size ) {
  245. my $size = $self->inner_window_size;
  246. $self->set_inner_window_size(@$size);
  247. }
  248. #Set debug if needed
  249. $self->debug_on() if $self->debug;
  250. # Setup non-croaking, parameter versions of finders
  251. foreach my $by ( keys %{ $self->FINDERS } ) {
  252. my $finder_name = 'find_element_by_' . $by;
  253. # In case we get instantiated multiple times, we don't want to
  254. # install into the name space every time.
  255. unless ( $self->can($finder_name) ) {
  256. my $find_sub = $self->_build_find_by($by);
  257. Sub::Install::install_sub(
  258. {
  259. code => $find_sub,
  260. into => __PACKAGE__,
  261. as => $finder_name,
  262. }
  263. );
  264. }
  265. }
  266. }
  267. sub new_from_caps {
  268. my ( $self, %args ) = @_;
  269. if ( not exists $args{desired_capabilities} ) {
  270. $args{desired_capabilities} = {};
  271. }
  272. return $self->new(%args);
  273. }
  274. sub DEMOLISH {
  275. my ( $self, $in_global_destruction ) = @_;
  276. return if $$ != $self->pid;
  277. return if $in_global_destruction;
  278. $self->quit() if ( $self->auto_close && defined $self->session_id );
  279. }
  280. # We install an 'around' because we can catch more exceptions this way
  281. # than simply wrapping the explicit croaks in _execute_command.
  282. # @args should be fed to the handler to provide context
  283. # return_value could be assigned from the handler if we want to allow the
  284. # error_handler to handle the errors
  285. around '_execute_command' => sub {
  286. my $orig = shift;
  287. my $self = shift;
  288. # copy @_ because it gets lost in the way
  289. my @args = @_;
  290. my $return_value;
  291. try {
  292. $return_value = $orig->( $self, @args );
  293. }
  294. catch {
  295. if ( $self->has_error_handler ) {
  296. $return_value = $self->error_handler->( $self, $_, @args );
  297. }
  298. else {
  299. croak $_;
  300. }
  301. };
  302. return $return_value;
  303. };
  304. sub _get_resource {
  305. my ( $self, $res ) = @_;
  306. return $self->commands_v3->get_params($res) if $self->{is_wd3};
  307. return $self->commands->get_params($res);
  308. }
  309. # This is an internal method used the Driver & is not supposed to be used by
  310. # end user. This method is used by Driver to set up all the parameters
  311. # (url & JSON), send commands & receive processed response from the server.
  312. sub _execute_command {
  313. my ( $self, $res, $params ) = @_;
  314. $res->{'session_id'} = $self->session_id;
  315. print "Prepping $res->{command}\n" if $self->{debug};
  316. #webdriver 3 shims
  317. return $self->{capabilities}
  318. if $res->{command} eq 'getCapabilities' && $self->{capabilities};
  319. $res->{ms} = $params->{ms} if $params->{ms};
  320. $res->{type} = $params->{type} if $params->{type};
  321. $res->{text} = $params->{text} if $params->{text};
  322. $res->{using} = $params->{using} if $params->{using};
  323. $res->{value} = $params->{value} if $params->{value};
  324. print "Executing $res->{command}\n" if $self->{debug};
  325. my $resource = $self->_get_resource($res);
  326. #Fall-back to legacy if wd3 command doesn't exist
  327. if ( !$resource && $self->{is_wd3} ) {
  328. print "Falling back to legacy selenium method for $res->{command}\n"
  329. if $self->{debug};
  330. $resource = $self->commands->get_params($res);
  331. }
  332. #XXX InternetExplorerDriver quirks
  333. if ( $self->{is_wd3} && $self->browser_name eq 'internet explorer' ) {
  334. delete $params->{ms};
  335. delete $params->{type};
  336. delete $resource->{payload}->{type};
  337. my $oldvalue = delete $params->{'page load'};
  338. $params->{pageLoad} = $oldvalue if $oldvalue;
  339. }
  340. if ($resource) {
  341. $params = {} unless $params;
  342. my $resp = $self->remote_conn->request( $resource, $params );
  343. #In general, the parse_response for v3 is better, which is why we use it *even if* we are falling back.
  344. return $self->commands_v3->parse_response( $res, $resp )
  345. if $self->{is_wd3};
  346. return $self->commands->parse_response( $res, $resp );
  347. }
  348. else {
  349. #Tell the use about the offending setting.
  350. croak "Couldn't retrieve command settings properly ".$res->{command}."\n";
  351. }
  352. }
  353. =head1 METHODS
  354. =head2 new_session (extra_capabilities)
  355. Make a new session on the server.
  356. Called by new(), not intended for regular use.
  357. Occaisonally handy for recovering from brower crashes.
  358. DANGER DANGER DANGER
  359. This will throw away your old session if you have not closed it!
  360. DANGER DANGER DANGER
  361. =cut
  362. sub new_session {
  363. my ( $self, $extra_capabilities ) = @_;
  364. $extra_capabilities ||= {};
  365. my $args = {
  366. 'desiredCapabilities' => {
  367. 'browserName' => $self->browser_name,
  368. 'platform' => $self->platform,
  369. 'javascriptEnabled' => $self->javascript,
  370. 'version' => $self->version // '',
  371. 'acceptSslCerts' => $self->accept_ssl_certs,
  372. %$extra_capabilities,
  373. },
  374. };
  375. $args->{'extra_capabilities'} = \%$extra_capabilities unless $FORCE_WD2;
  376. if ( defined $self->proxy ) {
  377. $args->{desiredCapabilities}->{proxy} = $self->proxy;
  378. }
  379. if ( $args->{desiredCapabilities}->{browserName} =~ /firefox/i
  380. && $self->has_firefox_profile )
  381. {
  382. $args->{desiredCapabilities}->{firefox_profile} =
  383. $self->firefox_profile->_encode;
  384. }
  385. $self->_request_new_session($args);
  386. }
  387. =head2 new_desired_session(capabilities)
  388. Basically the same as new_session, but with caps.
  389. Sort of an analog to new_from_caps.
  390. =cut
  391. sub new_desired_session {
  392. my ( $self, $caps ) = @_;
  393. $self->_request_new_session(
  394. {
  395. desiredCapabilities => $caps
  396. }
  397. );
  398. }
  399. sub _request_new_session {
  400. my ( $self, $args ) = @_;
  401. #XXX UGLY shim for webdriver3
  402. $args->{capabilities}->{alwaysMatch} =
  403. clone( $args->{desiredCapabilities} );
  404. my $cmap = $self->commands_v3->get_caps_map();
  405. my $caps = $self->commands_v3->get_caps();
  406. foreach my $cap ( keys( %{ $args->{capabilities}->{alwaysMatch} } ) ) {
  407. #Handle browser specific capabilities
  408. if ( exists( $args->{desiredCapabilities}->{browserName} )
  409. && $cap eq 'extra_capabilities' )
  410. {
  411. if (
  412. exists $args->{capabilities}->{alwaysMatch}
  413. ->{'moz:firefoxOptions'}->{args} )
  414. {
  415. $args->{capabilities}->{alwaysMatch}->{$cap}->{args} =
  416. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'}
  417. ->{args};
  418. }
  419. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'} =
  420. $args->{capabilities}->{alwaysMatch}->{$cap}
  421. if $args->{desiredCapabilities}->{browserName} eq 'firefox';
  422. #XXX the chrome documentation is lies, you can't do this yet
  423. #$args->{capabilities}->{alwaysMatch}->{'goog:chromeOptions'} = $args->{capabilities}->{alwaysMatch}->{$cap} if $args->{desiredCapabilities}->{browserName} eq 'chrome';
  424. #Does not appear there are any MSIE based options, so let's just let that be
  425. }
  426. if ( exists( $args->{desiredCapabilities}->{browserName} )
  427. && $args->{desiredCapabilities}->{browserName} eq 'firefox'
  428. && $cap eq 'firefox_profile' )
  429. {
  430. if (
  431. ref $args->{capabilities}->{alwaysMatch}->{$cap} eq
  432. 'Selenium::Firefox::Profile' )
  433. {
  434. #XXX not sure if I need to keep a ref to the File::Temp::Tempdir object to prevent reaping
  435. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'}
  436. ->{args} = [
  437. '-profile',
  438. $args->{capabilities}->{alwaysMatch}->{$cap}->{profile_dir}
  439. ->dirname()
  440. ];
  441. }
  442. else {
  443. #previously undocumented feature that we can pass the encoded profile
  444. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'}
  445. ->{profile} = $args->{capabilities}->{alwaysMatch}->{$cap};
  446. }
  447. }
  448. foreach my $newkey ( keys(%$cmap) ) {
  449. if ( $newkey eq $cap ) {
  450. last if $cmap->{$newkey} eq $cap;
  451. $args->{capabilities}->{alwaysMatch}->{ $cmap->{$newkey} } =
  452. $args->{capabilities}->{alwaysMatch}->{$cap};
  453. delete $args->{capabilities}->{alwaysMatch}->{$cap};
  454. last;
  455. }
  456. }
  457. delete $args->{capabilities}->{alwaysMatch}->{$cap}
  458. if !any { $_ eq $cap } @$caps;
  459. }
  460. delete $args->{desiredCapabilities}
  461. if $FORCE_WD3; #XXX fork working-around busted fallback in firefox
  462. delete $args->{capabilities}
  463. if $FORCE_WD2; #XXX 'secret' feature to help the legacy unit tests to work
  464. #Delete compatibility layer when using drivers directly
  465. if ( $self->isa('Selenium::Firefox') || $self->isa('Selenium::Chrome') || $self->isa('Selenium::Edge') ) {
  466. if ( exists $args->{capabilities}
  467. && exists $args->{capabilities}->{alwaysMatch} )
  468. {
  469. delete $args->{capabilities}->{alwaysMatch}->{browserName};
  470. delete $args->{capabilities}->{alwaysMatch}->{browserVersion};
  471. delete $args->{capabilities}->{alwaysMatch}->{platformName};
  472. }
  473. }
  474. #Fix broken out of the box chrome because they hate the maintainers of their interfaces
  475. if ( $self->isa('Selenium::Chrome') ) {
  476. if ( exists $args->{desiredCapabilities} ) {
  477. $args->{desiredCapabilities}{'goog:chromeOptions'}{args} //= [];
  478. push(@{$args->{desiredCapabilities}{'goog:chromeOptions'}{args}}, qw{no-sandbox disable-dev-shm-usage});
  479. }
  480. }
  481. # Die unless connection is good
  482. my $rc = $self->remote_conn;
  483. $rc->check_status();
  484. # command => 'newSession' to fool the tests of commands implemented
  485. # TODO: rewrite the testing better, this is so fragile.
  486. my $resource_new_session = {
  487. method => $self->commands->get_method('newSession'),
  488. url => $self->commands->get_url('newSession'),
  489. no_content_success =>
  490. $self->commands->get_no_content_success('newSession'),
  491. };
  492. my $resp = $rc->request( $resource_new_session, $args, );
  493. if ( $resp->{cmd_status} && $resp->{cmd_status} eq 'NOT OK' ) {
  494. croak "Could not obtain new session: ". $resp->{cmd_return}{message};
  495. }
  496. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  497. $self->session_id( $resp->{'sessionId'} );
  498. }
  499. else {
  500. my $error = 'Could not create new session';
  501. if ( ref $resp->{cmd_return} eq 'HASH' ) {
  502. $error .= ': ' . $resp->{cmd_return}->{message};
  503. }
  504. else {
  505. $error .= ': ' . $resp->{cmd_return};
  506. }
  507. croak $error;
  508. }
  509. #Webdriver 3 - best guess that this is 'whats goin on'
  510. if ( ref $resp->{cmd_return} eq 'HASH'
  511. && $resp->{cmd_return}->{capabilities} )
  512. {
  513. $self->{is_wd3} = 1;
  514. $self->{emulate_jsonwire} = 1;
  515. $self->{capabilities} = $resp->{cmd_return}->{capabilities};
  516. }
  517. #XXX chromedriver DOES NOT FOLLOW SPEC!
  518. if ( ref $resp->{cmd_return} eq 'HASH' && $resp->{cmd_return}->{chrome} ) {
  519. if ( defined $resp->{cmd_return}->{setWindowRect} )
  520. { #XXX i'm inferring we are wd3 based on the presence of this
  521. $self->{is_wd3} = 1;
  522. $self->{emulate_jsonwire} = 1;
  523. $self->{capabilities} = $resp->{cmd_return};
  524. }
  525. }
  526. #XXX unsurprisingly, neither does microsoft
  527. if ( ref $resp->{cmd_return} eq 'HASH'
  528. && $resp->{cmd_return}->{pageLoadStrategy}
  529. && $self->browser_name eq 'MicrosoftEdge' )
  530. {
  531. $self->{is_wd3} = 1;
  532. $self->{emulate_jsonwire} = 1;
  533. $self->{capabilities} = $resp->{cmd_return};
  534. }
  535. return ( $args, $resp );
  536. }
  537. =head2 is_webdriver_3
  538. Print whether the server (or browser) thinks it's implemented webdriver 3.
  539. If this returns true, webdriver 3 methods will be used in the case an action exists in L<Selenium::Remote::Spec> for the method you are trying to call.
  540. If a method you are calling has no webdriver 3 equivalent (or browser extension), the legacy commands implemented in L<Selenium::Remote::Commands> will be used.
  541. Note how I said *thinks* above. In the case you want to force usage of legacy methods, set $driver->{is_wd3} to work around various browser issues.
  542. =cut
  543. sub is_webdriver_3 {
  544. my $self = shift;
  545. return $self->{is_wd3};
  546. }
  547. =head2 debug_on
  548. Description:
  549. Turns on debugging mode and the driver will print extra info like request
  550. and response to stdout. Useful, when you want to see what is being sent to
  551. the server & what response you are getting back.
  552. Usage:
  553. $driver->debug_on;
  554. =cut
  555. sub debug_on {
  556. my ($self) = @_;
  557. $self->{debug} = 1;
  558. $self->remote_conn->debug(1);
  559. }
  560. =head2 debug_off
  561. Description:
  562. Turns off the debugging mode.
  563. Usage:
  564. $driver->debug_off;
  565. =cut
  566. sub debug_off {
  567. my ($self) = @_;
  568. $self->{debug} = 0;
  569. $self->remote_conn->debug(0);
  570. }
  571. =head2 get_sessions
  572. Description:
  573. Returns a list of the currently active sessions. Each session will be
  574. returned as an array of Hashes with the following keys:
  575. 'id' : The session ID
  576. 'capabilities: An object describing session's capabilities
  577. Output:
  578. Array of Hashes
  579. Usage:
  580. print Dumper $driver->get_sessions();
  581. =cut
  582. sub get_sessions {
  583. my ($self) = @_;
  584. my $res = { 'command' => 'getSessions' };
  585. return $self->_execute_command($res);
  586. }
  587. =head2 status
  588. Description:
  589. Query the server's current status. All server implementations
  590. should return two basic objects describing the server's current
  591. platform and when the server was built.
  592. Output:
  593. Hash ref
  594. Usage:
  595. print Dumper $driver->status;
  596. =cut
  597. sub status {
  598. my ($self) = @_;
  599. my $res = { 'command' => 'status' };
  600. return $self->_execute_command($res);
  601. }
  602. =head2 get_alert_text
  603. Description:
  604. Gets the text of the currently displayed JavaScript alert(), confirm()
  605. or prompt() dialog.
  606. Example
  607. my $string = $driver->get_alert_text;
  608. =cut
  609. sub get_alert_text {
  610. my ($self) = @_;
  611. my $res = { 'command' => 'getAlertText' };
  612. return $self->_execute_command($res);
  613. }
  614. =head2 send_keys_to_active_element
  615. Description:
  616. Send a sequence of key strokes to the active element. This command is
  617. similar to the send keys command in every aspect except the implicit
  618. termination: The modifiers are not released at the end of the call.
  619. Rather, the state of the modifier keys is kept between calls, so mouse
  620. interactions can be performed while modifier keys are depressed.
  621. Compatibility:
  622. On webdriver 3 servers, don't use this to send modifier keys; use send_modifier instead.
  623. Input: 1
  624. Required:
  625. {ARRAY | STRING} - Array of strings or a string.
  626. Usage:
  627. $driver->send_keys_to_active_element('abcd', 'efg');
  628. $driver->send_keys_to_active_element('hijk');
  629. or
  630. # include the WDKeys module
  631. use Selenium::Remote::WDKeys;
  632. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  633. =cut
  634. sub send_keys_to_active_element {
  635. my ( $self, @strings ) = @_;
  636. if ( $self->{is_wd3}
  637. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  638. {
  639. @strings = map { split( '', $_ ) } @strings;
  640. my @acts = map {
  641. (
  642. {
  643. type => 'keyDown',
  644. value => $_,
  645. },
  646. {
  647. type => 'keyUp',
  648. value => $_,
  649. }
  650. )
  651. } @strings;
  652. my $action = {
  653. actions => [
  654. {
  655. id => 'key',
  656. type => 'key',
  657. actions => \@acts,
  658. }
  659. ]
  660. };
  661. return $self->general_action(%$action);
  662. }
  663. my $res = { 'command' => 'sendKeysToActiveElement' };
  664. my $params = { 'value' => \@strings, };
  665. return $self->_execute_command( $res, $params );
  666. }
  667. =head2 send_keys_to_alert
  668. Synonymous with send_keys_to_prompt
  669. =cut
  670. sub send_keys_to_alert {
  671. return shift->send_keys_to_prompt(@_);
  672. }
  673. =head2 send_keys_to_prompt
  674. Description:
  675. Sends keystrokes to a JavaScript prompt() dialog.
  676. Input:
  677. {string} keys to send
  678. Example:
  679. $driver->send_keys_to_prompt('hello world');
  680. or
  681. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  682. $driver->send_keys_to_alert("Larry Wall");
  683. $driver->accept_alert;
  684. =cut
  685. sub send_keys_to_prompt {
  686. my ( $self, $keys ) = @_;
  687. my $res = { 'command' => 'sendKeysToPrompt' };
  688. my $params = { 'text' => $keys };
  689. return $self->_execute_command( $res, $params );
  690. }
  691. =head2 accept_alert
  692. Description:
  693. Accepts the currently displayed alert dialog. Usually, this is
  694. equivalent to clicking the 'OK' button in the dialog.
  695. Example:
  696. $driver->accept_alert;
  697. =cut
  698. sub accept_alert {
  699. my ($self) = @_;
  700. my $res = { 'command' => 'acceptAlert' };
  701. return $self->_execute_command($res);
  702. }
  703. =head2 dismiss_alert
  704. Description:
  705. Dismisses the currently displayed alert dialog. For comfirm()
  706. and prompt() dialogs, this is equivalent to clicking the
  707. 'Cancel' button. For alert() dialogs, this is equivalent to
  708. clicking the 'OK' button.
  709. Example:
  710. $driver->dismiss_alert;
  711. =cut
  712. sub dismiss_alert {
  713. my ($self) = @_;
  714. my $res = { 'command' => 'dismissAlert' };
  715. return $self->_execute_command($res);
  716. }
  717. =head2 general_action
  718. Provide an 'actions definition' hash to make webdriver use input devices.
  719. Given the spec for the structure of this data is 'non normative',
  720. it is left as an exercise to the reader what that means as to how to use this function.
  721. That said, it seems most of the data looks something like this:
  722. $driver->general_action( actions => [{
  723. type => 'pointer|key|none|somethingElseSuperSpecialDefinedByYourBrowserDriver',
  724. id => MUST be mouse|key|none|other. And by 'other' I mean anything else. The first 3 are 'special' in that they are used in the global actions queue.
  725. If you want say, another mouse action to execute in parallel to other mouse actions (to simulate multi-touch, for example), call your action 'otherMouseAction' or something.
  726. parameters => {
  727. someOption => "basically these are global parameters used by all steps in the forthcoming "action chain".
  728. },
  729. actions => [
  730. {
  731. type => "keyUp|KeyDown if key, pointerUp|pointerDown|pointerMove|pointerCancel if pointer, pause if any type",
  732. key => A raw keycode or character from the keyboard if this is a key event,
  733. duration => how many 'ticks' this action should take, you probably want this to be 0 all of the time unless you are evading Software debounce.
  734. button => what number button if you are using a pointer (this sounds terribly like it might be re-purposed to be a joypad in the future sometime)
  735. origin => Point of Origin if moving a pointer around
  736. x => unit vector to travel along x-axis if pointerMove event
  737. y => unit vector to travel along y-axis if pointerMove event
  738. },
  739. ...
  740. ]
  741. },
  742. ...
  743. ]
  744. )
  745. Only available on WebDriver3 capable selenium servers.
  746. If you have called any legacy shim, such as mouse_move_to_location() previously, your actions passed will be appended to the existing actions queue.
  747. Called with no arguments, it simply executes the existing action queue.
  748. If you are looking for pre-baked action chains that aren't currently part of L<Selenium::Remote::Driver>,
  749. consider L<Selenium::ActionChains>, which is shipped with this distribution instead.
  750. =head3 COMPATIBILITY
  751. Like most places, the WC3 standard is openly ignored by the driver binaries.
  752. Generally an "actions" object will only accept:
  753. { type => ..., value => ... }
  754. When using the direct drivers (E.G. Selenium::Chrome, Selenium::Firefox).
  755. This is not documented anywhere but here, as far as I can tell.
  756. =cut
  757. sub general_action {
  758. my ( $self, %action ) = @_;
  759. _queue_action(%action);
  760. my $res = { 'command' => 'generalAction' };
  761. my $out = $self->_execute_command( $res, \%CURRENT_ACTION_CHAIN );
  762. %CURRENT_ACTION_CHAIN = ( actions => [] );
  763. return $out;
  764. }
  765. sub _queue_action {
  766. my (%action) = @_;
  767. if ( ref $action{actions} eq 'ARRAY' ) {
  768. foreach my $live_action ( @{ $action{actions} } ) {
  769. my $existing_action;
  770. foreach my $global_action ( @{ $CURRENT_ACTION_CHAIN{actions} } ) {
  771. if ( $global_action->{id} eq $live_action->{id} ) {
  772. $existing_action = $global_action;
  773. last;
  774. }
  775. }
  776. if ($existing_action) {
  777. push(
  778. @{ $existing_action->{actions} },
  779. @{ $live_action->{actions} }
  780. );
  781. }
  782. else {
  783. push( @{ $CURRENT_ACTION_CHAIN{actions} }, $live_action );
  784. }
  785. }
  786. }
  787. }
  788. =head2 release_general_action
  789. Nukes *all* input device state (modifier key up/down, pointer button up/down, pointer location, and other device state) from orbit.
  790. Call if you forget to do a *Up event in your provided action chains, or just to save time.
  791. Also clears the current actions queue.
  792. Only available on WebDriver3 capable selenium servers.
  793. =cut
  794. sub release_general_action {
  795. my ($self) = @_;
  796. my $res = { 'command' => 'releaseGeneralAction' };
  797. %CURRENT_ACTION_CHAIN = ( actions => [] );
  798. return $self->_execute_command($res);
  799. }
  800. =head2 mouse_move_to_location
  801. Description:
  802. Move the mouse by an offset of the specificed element. If no
  803. element is specified, the move is relative to the current mouse
  804. cursor. If an element is provided but no offset, the mouse will be
  805. moved to the center of the element. If the element is not visible,
  806. it will be scrolled into view.
  807. Compatibility:
  808. Due to limitations in the Webdriver 3 API, mouse movements have to be executed 'lazily' e.g. only right before a click() event occurs.
  809. This is because there is no longer any persistent mouse location state; mouse movements are now totally atomic.
  810. This has several problematic aspects; for one, I can't think of a way to both hover an element and then do another action relying on the element staying hover()ed,
  811. Aside from using javascript workarounds.
  812. Output:
  813. STRING -
  814. Usage:
  815. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  816. # 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.
  817. # 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.
  818. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  819. =cut
  820. sub mouse_move_to_location {
  821. my ( $self, %params ) = @_;
  822. $params{element} = $params{element}{id} if exists $params{element};
  823. if ( $self->{is_wd3}
  824. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  825. {
  826. my $origin = $params{element};
  827. my $move_action = {
  828. type => "pointerMove",
  829. duration => 0,
  830. x => $params{xoffset} // 0,
  831. y => $params{yoffset} // 0,
  832. };
  833. $move_action->{origin} =
  834. { 'element-6066-11e4-a52e-4f735466cecf' => $origin }
  835. if $origin;
  836. _queue_action(
  837. actions => [
  838. {
  839. type => "pointer",
  840. id => 'mouse',
  841. "parameters" => { "pointerType" => "mouse" },
  842. actions => [$move_action],
  843. }
  844. ]
  845. );
  846. return 1;
  847. }
  848. my $res = { 'command' => 'mouseMoveToLocation' };
  849. return $self->_execute_command( $res, \%params );
  850. }
  851. =head2 move_to
  852. Synonymous with mouse_move_to_location
  853. =cut
  854. sub move_to {
  855. return shift->mouse_move_to_location(@_);
  856. }
  857. =head2 get_capabilities
  858. Description:
  859. Retrieve the capabilities of the specified session.
  860. Output:
  861. HASH of all the capabilities.
  862. Usage:
  863. my $capab = $driver->get_capabilities();
  864. print Dumper($capab);
  865. =cut
  866. sub get_capabilities {
  867. my $self = shift;
  868. my $res = { 'command' => 'getCapabilities' };
  869. return $self->_execute_command($res);
  870. }
  871. =head2 get_timeouts
  872. Description:
  873. Get the currently configured values (ms) for the page load, script and implicit timeouts.
  874. Compatibility:
  875. Only available on WebDriver3 enabled selenium servers.
  876. Usage:
  877. $driver->get_timeouts();
  878. =cut
  879. sub get_timeouts {
  880. my $self = shift;
  881. my $res = { 'command' => 'getTimeouts' };
  882. return $self->_execute_command( $res, {} );
  883. }
  884. =head2 set_timeout
  885. Description:
  886. Configure the amount of time that a particular type of operation can execute
  887. for before they are aborted and a |Timeout| error is returned to the client.
  888. Input:
  889. type - <STRING> - The type of operation to set the timeout for.
  890. Valid values are:
  891. "script" : for script timeouts,
  892. "implicit" : for modifying the implicit wait timeout
  893. "page load" : for setting a page load timeout.
  894. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  895. commands are permitted to run.
  896. Usage:
  897. $driver->set_timeout('script', 1000);
  898. =cut
  899. sub set_timeout {
  900. my ( $self, $type, $ms ) = @_;
  901. if ( not defined $type ) {
  902. croak "Expecting type";
  903. }
  904. $ms = _coerce_timeout_ms($ms);
  905. $type = 'pageLoad'
  906. if $type eq 'page load'
  907. && $self->browser_name ne
  908. 'MicrosoftEdge'; #XXX SHIM they changed the WC3 standard mid stream
  909. my $res = { 'command' => 'setTimeout' };
  910. my $params = { $type => $ms };
  911. #XXX edge still follows earlier versions of the WC3 standard
  912. if ( $self->browser_name eq 'MicrosoftEdge' ) {
  913. $params->{ms} = $ms;
  914. $params->{type} = $type;
  915. }
  916. return $self->_execute_command( $res, $params );
  917. }
  918. =head2 set_async_script_timeout
  919. Description:
  920. Set the amount of time, in milliseconds, that asynchronous scripts executed
  921. by execute_async_script() are permitted to run before they are
  922. aborted and a |Timeout| error is returned to the client.
  923. Input:
  924. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  925. commands are permitted to run.
  926. Usage:
  927. $driver->set_async_script_timeout(1000);
  928. =cut
  929. sub set_async_script_timeout {
  930. my ( $self, $ms ) = @_;
  931. return $self->set_timeout( 'script', $ms ) if $self->{is_wd3};
  932. $ms = _coerce_timeout_ms($ms);
  933. my $res = { 'command' => 'setAsyncScriptTimeout' };
  934. my $params = { 'ms' => $ms };
  935. return $self->_execute_command( $res, $params );
  936. }
  937. =head2 set_implicit_wait_timeout
  938. Description:
  939. Set the amount of time the driver should wait when searching for elements.
  940. When searching for a single element, the driver will poll the page until
  941. an element is found or the timeout expires, whichever occurs first.
  942. When searching for multiple elements, the driver should poll the page until
  943. at least one element is found or the timeout expires, at which point it
  944. will return an empty list. If this method is never called, the driver will
  945. default to an implicit wait of 0ms.
  946. This is exactly equivalent to calling L</set_timeout> with a type
  947. arg of C<"implicit">.
  948. Input:
  949. Time in milliseconds.
  950. Output:
  951. Server Response Hash with no data returned back from the server.
  952. Usage:
  953. $driver->set_implicit_wait_timeout(10);
  954. =cut
  955. sub set_implicit_wait_timeout {
  956. my ( $self, $ms ) = @_;
  957. return $self->set_timeout( 'implicit', $ms ) if $self->{is_wd3};
  958. $ms = _coerce_timeout_ms($ms);
  959. my $res = { 'command' => 'setImplicitWaitTimeout' };
  960. my $params = { 'ms' => $ms };
  961. return $self->_execute_command( $res, $params );
  962. }
  963. =head2 pause
  964. Description:
  965. Pause execution for a specified interval of milliseconds.
  966. Usage:
  967. $driver->pause(10000); # 10 second delay
  968. $driver->pause(); # 1 second delay default
  969. DEPRECATED: consider using Time::HiRes instead.
  970. =cut
  971. sub pause {
  972. my $self = shift;
  973. my $timeout = ( shift // 1000 ) * 1000;
  974. usleep($timeout);
  975. }
  976. =head2 close
  977. Description:
  978. Close the current window.
  979. Usage:
  980. $driver->close();
  981. or
  982. #close a popup window
  983. my $handles = $driver->get_window_handles;
  984. $driver->switch_to_window($handles->[1]);
  985. $driver->close();
  986. $driver->switch_to_window($handles->[0]);
  987. =cut
  988. sub close {
  989. my $self = shift;
  990. my $res = { 'command' => 'close' };
  991. $self->_execute_command($res);
  992. }
  993. =head2 quit
  994. Description:
  995. DELETE the session, closing open browsers. We will try to call
  996. this on our down when we get destroyed, but in the event that we
  997. are demolished during global destruction, we will not be able to
  998. close the browser. For your own unattended and/or complicated
  999. tests, we recommend explicitly calling quit to make sure you're
  1000. not leaving orphan browsers around.
  1001. Note that as a Moo class, we use a subroutine called DEMOLISH that
  1002. takes the place of DESTROY; for more information, see
  1003. https://metacpan.org/pod/Moo#DEMOLISH.
  1004. Usage:
  1005. $driver->quit();
  1006. =cut
  1007. sub quit {
  1008. my $self = shift;
  1009. my $res = { 'command' => 'quit' };
  1010. $self->_execute_command($res);
  1011. $self->session_id(undef);
  1012. }
  1013. =head2 get_current_window_handle
  1014. Description:
  1015. Retrieve the current window handle.
  1016. Output:
  1017. STRING - the window handle
  1018. Usage:
  1019. print $driver->get_current_window_handle();
  1020. =cut
  1021. sub get_current_window_handle {
  1022. my $self = shift;
  1023. my $res = { 'command' => 'getCurrentWindowHandle' };
  1024. return $self->_execute_command($res);
  1025. }
  1026. =head2 get_window_handles
  1027. Description:
  1028. Retrieve the list of window handles used in the session.
  1029. Output:
  1030. ARRAY of STRING - list of the window handles
  1031. Usage:
  1032. print Dumper $driver->get_window_handles;
  1033. or
  1034. # get popup, close, then back
  1035. my $handles = $driver->get_window_handles;
  1036. $driver->switch_to_window($handles->[1]);
  1037. $driver->close;
  1038. $driver->switch_to_window($handles->[0]);
  1039. =cut
  1040. sub get_window_handles {
  1041. my $self = shift;
  1042. my $res = { 'command' => 'getWindowHandles' };
  1043. return $self->_execute_command($res);
  1044. }
  1045. =head2 get_window_size
  1046. Description:
  1047. Retrieve the window size
  1048. Compatibility:
  1049. The ability to get the size of arbitrary handles by passing input only exists in WebDriver2.
  1050. You will have to switch to the window first going forward.
  1051. Input:
  1052. STRING - <optional> - window handle (default is 'current' window)
  1053. Output:
  1054. HASH - containing keys 'height' & 'width'
  1055. Usage:
  1056. my $window_size = $driver->get_window_size();
  1057. print $window_size->{'height'}, $window_size->{'width'};
  1058. =cut
  1059. sub get_window_size {
  1060. my ( $self, $window ) = @_;
  1061. $window = ( defined $window ) ? $window : 'current';
  1062. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  1063. $res = { 'command' => 'getWindowRect', handle => $window }
  1064. if $self->{is_wd3};
  1065. return $self->_execute_command($res);
  1066. }
  1067. =head2 get_window_position
  1068. Description:
  1069. Retrieve the window position
  1070. Compatibility:
  1071. The ability to get the size of arbitrary handles by passing input only exists in WebDriver2.
  1072. You will have to switch to the window first going forward.
  1073. Input:
  1074. STRING - <optional> - window handle (default is 'current' window)
  1075. Output:
  1076. HASH - containing keys 'x' & 'y'
  1077. Usage:
  1078. my $window_size = $driver->get_window_position();
  1079. print $window_size->{'x'}, $window_size->('y');
  1080. =cut
  1081. sub get_window_position {
  1082. my ( $self, $window ) = @_;
  1083. $window = ( defined $window ) ? $window : 'current';
  1084. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  1085. $res = { 'command' => 'getWindowRect', handle => $window }
  1086. if $self->{is_wd3};
  1087. return $self->_execute_command($res);
  1088. }
  1089. =head2 get_current_url
  1090. Description:
  1091. Retrieve the url of the current page
  1092. Output:
  1093. STRING - url
  1094. Usage:
  1095. print $driver->get_current_url();
  1096. =cut
  1097. sub get_current_url {
  1098. my $self = shift;
  1099. my $res = { 'command' => 'getCurrentUrl' };
  1100. return $self->_execute_command($res);
  1101. }
  1102. =head2 navigate
  1103. Description:
  1104. Navigate to a given url. This is same as get() method.
  1105. Input:
  1106. STRING - url
  1107. Usage:
  1108. $driver->navigate('http://www.google.com');
  1109. =cut
  1110. sub navigate {
  1111. my ( $self, $url ) = @_;
  1112. $self->get($url);
  1113. }
  1114. =head2 get
  1115. Description:
  1116. Navigate to a given url
  1117. Input:
  1118. STRING - url
  1119. Usage:
  1120. $driver->get('http://www.google.com');
  1121. =cut
  1122. sub get {
  1123. my ( $self, $url ) = @_;
  1124. if ( $self->has_base_url && $url !~ m|://| ) {
  1125. $url =~ s|^/||;
  1126. $url = $self->base_url . "/" . $url;
  1127. }
  1128. my $res = { 'command' => 'get' };
  1129. my $params = { 'url' => $url };
  1130. return $self->_execute_command( $res, $params );
  1131. }
  1132. =head2 get_title
  1133. Description:
  1134. Get the current page title
  1135. Output:
  1136. STRING - Page title
  1137. Usage:
  1138. print $driver->get_title();
  1139. =cut
  1140. sub get_title {
  1141. my $self = shift;
  1142. my $res = { 'command' => 'getTitle' };
  1143. return $self->_execute_command($res);
  1144. }
  1145. =head2 go_back
  1146. Description:
  1147. Equivalent to hitting the back button on the browser.
  1148. Usage:
  1149. $driver->go_back();
  1150. =cut
  1151. sub go_back {
  1152. my $self = shift;
  1153. my $res = { 'command' => 'goBack' };
  1154. return $self->_execute_command($res);
  1155. }
  1156. =head2 go_forward
  1157. Description:
  1158. Equivalent to hitting the forward button on the browser.
  1159. Usage:
  1160. $driver->go_forward();
  1161. =cut
  1162. sub go_forward {
  1163. my $self = shift;
  1164. my $res = { 'command' => 'goForward' };
  1165. return $self->_execute_command($res);
  1166. }
  1167. =head2 refresh
  1168. Description:
  1169. Reload the current page.
  1170. Usage:
  1171. $driver->refresh();
  1172. =cut
  1173. sub refresh {
  1174. my $self = shift;
  1175. my $res = { 'command' => 'refresh' };
  1176. return $self->_execute_command($res);
  1177. }
  1178. =head2 has_javascript
  1179. Description:
  1180. returns true if javascript is enabled in the driver.
  1181. Compatibility:
  1182. Can't be false on WebDriver 3.
  1183. Usage:
  1184. if ($driver->has_javascript) { ...; }
  1185. =cut
  1186. sub has_javascript {
  1187. my $self = shift;
  1188. return int( $self->javascript );
  1189. }
  1190. =head2 execute_async_script
  1191. Description:
  1192. Inject a snippet of JavaScript into the page for execution in the context
  1193. of the currently selected frame. The executed script is assumed to be
  1194. asynchronous and must signal that is done by invoking the provided
  1195. callback, which is always provided as the final argument to the function.
  1196. The value to this callback will be returned to the client.
  1197. Asynchronous script commands may not span page loads. If an unload event
  1198. is fired while waiting for a script result, an error should be returned
  1199. to the client.
  1200. Input: 2 (1 optional)
  1201. Required:
  1202. STRING - Javascript to execute on the page
  1203. Optional:
  1204. ARRAY - list of arguments that need to be passed to the script.
  1205. Output:
  1206. {*} - Varied, depending on the type of result expected back from the script.
  1207. Usage:
  1208. my $script = q{
  1209. var arg1 = arguments[0];
  1210. var callback = arguments[arguments.length-1];
  1211. var elem = window.document.findElementById(arg1);
  1212. callback(elem);
  1213. };
  1214. my $elem = $driver->execute_async_script($script,'myid');
  1215. $elem->click;
  1216. =cut
  1217. sub execute_async_script {
  1218. my ( $self, $script, @args ) = @_;
  1219. if ( $self->has_javascript ) {
  1220. if ( not defined $script ) {
  1221. croak 'No script provided';
  1222. }
  1223. my $res =
  1224. { 'command' => 'executeAsyncScript' . $self->_execute_script_suffix };
  1225. # Check the args array if the elem obj is provided & replace it with
  1226. # JSON representation
  1227. for ( my $i = 0 ; $i < @args ; $i++ ) {
  1228. if ( Scalar::Util::blessed( $args[$i] )
  1229. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1230. {
  1231. if ( $self->{is_wd3} ) {
  1232. $args[$i] =
  1233. { 'element-6066-11e4-a52e-4f735466cecf' =>
  1234. ( $args[$i] )->{id} };
  1235. }
  1236. else {
  1237. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1238. }
  1239. }
  1240. }
  1241. my $params = { 'script' => $script, 'args' => \@args };
  1242. my $ret = $self->_execute_command( $res, $params );
  1243. # replace any ELEMENTS with WebElement
  1244. if ( ref($ret)
  1245. and ( ref($ret) eq 'HASH' )
  1246. and $self->_looks_like_element($ret) )
  1247. {
  1248. $ret = $self->webelement_class->new(
  1249. id => $ret,
  1250. driver => $self
  1251. );
  1252. }
  1253. return $ret;
  1254. }
  1255. else {
  1256. croak 'Javascript is not enabled on remote driver instance.';
  1257. }
  1258. }
  1259. =head2 execute_script
  1260. Description:
  1261. Inject a snippet of JavaScript into the page and return its result.
  1262. WebElements that should be passed to the script as an argument should be
  1263. specified in the arguments array as WebElement object. Likewise,
  1264. any WebElements in the script result will be returned as WebElement object.
  1265. Input: 2 (1 optional)
  1266. Required:
  1267. STRING - Javascript to execute on the page
  1268. Optional:
  1269. ARRAY - list of arguments that need to be passed to the script.
  1270. Output:
  1271. {*} - Varied, depending on the type of result expected back from the script.
  1272. Usage:
  1273. my $script = q{
  1274. var arg1 = arguments[0];
  1275. var elem = window.document.findElementById(arg1);
  1276. return elem;
  1277. };
  1278. my $elem = $driver->execute_script($script,'myid');
  1279. $elem->click;
  1280. =cut
  1281. sub execute_script {
  1282. my ( $self, $script, @args ) = @_;
  1283. if ( $self->has_javascript ) {
  1284. if ( not defined $script ) {
  1285. croak 'No script provided';
  1286. }
  1287. my $res =
  1288. { 'command' => 'executeScript' . $self->_execute_script_suffix };
  1289. # Check the args array if the elem obj is provided & replace it with
  1290. # JSON representation
  1291. for ( my $i = 0 ; $i < @args ; $i++ ) {
  1292. if ( Scalar::Util::blessed( $args[$i] )
  1293. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1294. {
  1295. if ( $self->{is_wd3} ) {
  1296. $args[$i] =
  1297. { 'element-6066-11e4-a52e-4f735466cecf' =>
  1298. ( $args[$i] )->{id} };
  1299. }
  1300. else {
  1301. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1302. }
  1303. }
  1304. }
  1305. my $params = { 'script' => $script, 'args' => [@args] };
  1306. my $ret = $self->_execute_command( $res, $params );
  1307. return $self->_convert_to_webelement($ret);
  1308. }
  1309. else {
  1310. croak 'Javascript is not enabled on remote driver instance.';
  1311. }
  1312. }
  1313. # _looks_like_element
  1314. # An internal method to check if a return value might be an element
  1315. sub _looks_like_element {
  1316. my ( $self, $maybe_element ) = @_;
  1317. return (
  1318. exists $maybe_element->{ELEMENT}
  1319. or exists $maybe_element->{'element-6066-11e4-a52e-4f735466cecf'}
  1320. );
  1321. }
  1322. # _convert_to_webelement
  1323. # An internal method used to traverse a data structure
  1324. # and convert any ELEMENTS with WebElements
  1325. sub _convert_to_webelement {
  1326. my ( $self, $ret ) = @_;
  1327. if ( ref($ret) and ( ref($ret) eq 'HASH' ) ) {
  1328. if ( $self->_looks_like_element($ret) ) {
  1329. # replace an ELEMENT with WebElement
  1330. return $self->webelement_class->new(
  1331. id => $ret,
  1332. driver => $self
  1333. );
  1334. }
  1335. my %hash;
  1336. foreach my $key ( keys %$ret ) {
  1337. $hash{$key} = $self->_convert_to_webelement( $ret->{$key} );
  1338. }
  1339. return \%hash;
  1340. }
  1341. if ( ref($ret) and ( ref($ret) eq 'ARRAY' ) ) {
  1342. my @array = map { $self->_convert_to_webelement($_) } @$ret;
  1343. return \@array;
  1344. }
  1345. return $ret;
  1346. }
  1347. =head2 screenshot
  1348. Description:
  1349. Get a screenshot of the current page as a base64 encoded image.
  1350. Optionally pass {'full' => 1} as argument to take a full screenshot and not
  1351. only the viewport. (Works only with firefox and geckodriver >= 0.24.0)
  1352. Output:
  1353. STRING - base64 encoded image
  1354. Usage:
  1355. print $driver->screenshot();
  1356. print $driver->screenshot({'full' => 1});
  1357. To conveniently write the screenshot to a file, see L</capture_screenshot>.
  1358. =cut
  1359. sub screenshot {
  1360. my ($self, $params) = @_;
  1361. $params //= { full => 0 };
  1362. croak "Full page screenshot only supported on geckodriver" if $params->{full} && ( $self->{browser_name} ne 'firefox' );
  1363. my $res = { 'command' => $params->{'full'} == 1 ? 'mozScreenshotFull' : 'screenshot' };
  1364. return $self->_execute_command($res);
  1365. }
  1366. =head2 capture_screenshot
  1367. Description:
  1368. Capture a screenshot and save as a PNG to provided file name.
  1369. (The method is compatible with the WWW::Selenium method of the same name)
  1370. Optionally pass {'full' => 1} as second argument to take a full screenshot
  1371. and not only the viewport. (Works only with firefox and geckodriver >= 0.24.0)
  1372. Output:
  1373. TRUE - (Screenshot is written to file)
  1374. Usage:
  1375. $driver->capture_screenshot($filename);
  1376. $driver->capture_screenshot($filename, {'full' => 1});
  1377. =cut
  1378. sub capture_screenshot {
  1379. my ( $self, $filename, $params ) = @_;
  1380. croak '$filename is required' unless $filename;
  1381. open( my $fh, '>', $filename );
  1382. binmode $fh;
  1383. print $fh MIME::Base64::decode_base64( $self->screenshot($params) );
  1384. CORE::close $fh;
  1385. return 1;
  1386. }
  1387. =head2 available_engines
  1388. Description:
  1389. List all available engines on the machine. To use an engine, it has to be present in this list.
  1390. Compatibility:
  1391. Does not appear to be available on Webdriver3 enabled selenium servers.
  1392. Output:
  1393. {Array.<string>} A list of available engines
  1394. Usage:
  1395. print Dumper $driver->available_engines;
  1396. =cut
  1397. #TODO emulate behavior on wd3?
  1398. #grep { eval { Selenium::Remote::Driver->new( browser => $_ ) } } (qw{firefox MicrosoftEdge chrome opera safari htmlunit iphone phantomjs},'internet_explorer');
  1399. #might do the trick
  1400. sub available_engines {
  1401. my ($self) = @_;
  1402. my $res = { 'command' => 'availableEngines' };
  1403. return $self->_execute_command($res);
  1404. }
  1405. =head2 switch_to_frame
  1406. Description:
  1407. Change focus to another frame on the page. If the frame ID is null, the
  1408. server will switch to the page's default content. You can also switch to a
  1409. WebElement, for e.g. you can find an iframe using find_element & then
  1410. provide that as an input to this method. Also see e.g.
  1411. Input: 1
  1412. Required:
  1413. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  1414. mentioned.
  1415. Usage:
  1416. $driver->switch_to_frame('frame_1');
  1417. or
  1418. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  1419. =head3 COMPATIBILITY
  1420. Chromedriver will vomit if you pass anything but a webElement, so you probably should do that from now on.
  1421. =cut
  1422. sub switch_to_frame {
  1423. my ( $self, $id ) = @_;
  1424. my $json_null = JSON::null;
  1425. my $params;
  1426. $id = ( defined $id ) ? $id : $json_null;
  1427. my $res = { 'command' => 'switchToFrame' };
  1428. if ( ref $id eq $self->webelement_class ) {
  1429. if ( $self->{is_wd3} ) {
  1430. $params =
  1431. { 'id' =>
  1432. { 'element-6066-11e4-a52e-4f735466cecf' => $id->{'id'} } };
  1433. }
  1434. else {
  1435. $params = { 'id' => { 'ELEMENT' => $id->{'id'} } };
  1436. }
  1437. }
  1438. else {
  1439. $params = { 'id' => $id };
  1440. }
  1441. return $self->_execute_command( $res, $params );
  1442. }
  1443. =head2 switch_to_parent_frame
  1444. Webdriver 3 equivalent of calling switch_to_frame with no arguments (e.g. NULL frame).
  1445. This is actually called in that case, supposing you are using WD3 capable servers now.
  1446. =cut
  1447. sub switch_to_parent_frame {
  1448. my ($self) = @_;
  1449. my $res = { 'command' => 'switchToParentFrame' };
  1450. return $self->_execute_command($res);
  1451. }
  1452. =head2 switch_to_window
  1453. Description:
  1454. Change focus to another window. The window to change focus to may
  1455. be specified by its server assigned window handle, or by the value
  1456. of the page's window.name attribute.
  1457. If you wish to use the window name as the target, you'll need to
  1458. have set C<window.name> on the page either in app code or via
  1459. L</execute_script>, or pass a name as the second argument to the
  1460. C<window.open()> function when opening the new window. Note that
  1461. the window name used here has nothing to do with the window title,
  1462. or the C<< <title> >> element on the page.
  1463. Otherwise, use L</get_window_handles> and select a
  1464. Webdriver-generated handle from the output of that function.
  1465. Input: 1
  1466. Required:
  1467. STRING - Window handle or the Window name
  1468. Usage:
  1469. $driver->switch_to_window('MY Homepage');
  1470. or
  1471. # close a popup window and switch back
  1472. my $handles = $driver->get_window_handles;
  1473. $driver->switch_to_window($handles->[1]);
  1474. $driver->close;
  1475. $driver->switch_to_window($handles->[0]);
  1476. =cut
  1477. sub switch_to_window {
  1478. my ( $self, $name ) = @_;
  1479. if ( not defined $name ) {
  1480. return 'Window name not provided';
  1481. }
  1482. my $res = { 'command' => 'switchToWindow' };
  1483. my $params = { 'name' => $name, 'handle' => $name };
  1484. return $self->_execute_command( $res, $params );
  1485. }
  1486. =head2 set_window_position
  1487. Description:
  1488. Set the position (on screen) where you want your browser to be displayed.
  1489. Compatibility:
  1490. In webDriver 3 enabled selenium servers, you may only operate on the focused window.
  1491. As such, the window handle argument below will be ignored in this context.
  1492. Input:
  1493. INT - x co-ordinate
  1494. INT - y co-ordinate
  1495. STRING - <optional> - window handle (default is 'current' window)
  1496. Output:
  1497. BOOLEAN - Success or failure
  1498. Usage:
  1499. $driver->set_window_position(50, 50);
  1500. =cut
  1501. sub set_window_position {
  1502. my ( $self, $x, $y, $window ) = @_;
  1503. $window = ( defined $window ) ? $window : 'current';
  1504. if ( not defined $x and not defined $y ) {
  1505. croak "X & Y co-ordinates are required";
  1506. }
  1507. croak qq{Error: In set_window_size, argument x "$x" isn't numeric}
  1508. unless Scalar::Util::looks_like_number($x);
  1509. croak qq{Error: In set_window_size, argument y "$y" isn't numeric}
  1510. unless Scalar::Util::looks_like_number($y);
  1511. $x +=
  1512. 0; # convert to numeric if a string, otherwise they'll be sent as strings
  1513. $y += 0;
  1514. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1515. my $params = { 'x' => $x, 'y' => $y };
  1516. if ( $self->{is_wd3} ) {
  1517. $res = { 'command' => 'setWindowRect', handle => $window };
  1518. }
  1519. my $ret = $self->_execute_command( $res, $params );
  1520. return $ret ? 1 : 0;
  1521. }
  1522. =head2 set_window_size
  1523. Description:
  1524. Set the size of the browser window
  1525. Compatibility:
  1526. In webDriver 3 enabled selenium servers, you may only operate on the focused window.
  1527. As such, the window handle argument below will be ignored in this context.
  1528. Input:
  1529. INT - height of the window
  1530. INT - width of the window
  1531. STRING - <optional> - window handle (default is 'current' window)
  1532. Output:
  1533. BOOLEAN - Success or failure
  1534. Usage:
  1535. $driver->set_window_size(640, 480);
  1536. =cut
  1537. sub set_window_size {
  1538. my ( $self, $height, $width, $window ) = @_;
  1539. $window = ( defined $window ) ? $window : 'current';
  1540. if ( not defined $height and not defined $width ) {
  1541. croak "height & width of browser are required";
  1542. }
  1543. croak qq{Error: In set_window_size, argument height "$height" isn't numeric}
  1544. unless Scalar::Util::looks_like_number($height);
  1545. croak qq{Error: In set_window_size, argument width "$width" isn't numeric}
  1546. unless Scalar::Util::looks_like_number($width);
  1547. $height +=
  1548. 0; # convert to numeric if a string, otherwise they'll be sent as strings
  1549. $width += 0;
  1550. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1551. my $params = { 'height' => $height, 'width' => $width };
  1552. if ( $self->{is_wd3} ) {
  1553. $res = { 'command' => 'setWindowRect', handle => $window };
  1554. }
  1555. my $ret = $self->_execute_command( $res, $params );
  1556. return $ret ? 1 : 0;
  1557. }
  1558. =head2 maximize_window
  1559. Description:
  1560. Maximizes the browser window
  1561. Compatibility:
  1562. In webDriver 3 enabled selenium servers, you may only operate on the focused window.
  1563. As such, the window handle argument below will be ignored in this context.
  1564. Also, on chromedriver maximize is actually just setting the window size to the screen's
  1565. available height and width.
  1566. Input:
  1567. STRING - <optional> - window handle (default is 'current' window)
  1568. Output:
  1569. BOOLEAN - Success or failure
  1570. Usage:
  1571. $driver->maximize_window();
  1572. =cut
  1573. sub maximize_window {
  1574. my ( $self, $window ) = @_;
  1575. $window = ( defined $window ) ? $window : 'current';
  1576. my $res = { 'command' => 'maximizeWindow', 'window_handle' => $window };
  1577. my $ret = $self->_execute_command($res);
  1578. return $ret ? 1 : 0;
  1579. }
  1580. =head2 minimize_window
  1581. Description:
  1582. Minimizes the currently focused browser window (webdriver3 only)
  1583. Output:
  1584. BOOLEAN - Success or failure
  1585. Usage:
  1586. $driver->minimize_window();
  1587. =cut
  1588. sub minimize_window {
  1589. my ( $self, $window ) = @_;
  1590. $window = ( defined $window ) ? $window : 'current';
  1591. my $res = { 'command' => 'minimizeWindow', 'window_handle' => $window };
  1592. my $ret = $self->_execute_command($res);
  1593. return $ret ? 1 : 0;
  1594. }
  1595. =head2 fullscreen_window
  1596. Description:
  1597. Fullscreens the currently focused browser window (webdriver3 only)
  1598. Output:
  1599. BOOLEAN - Success or failure
  1600. Usage:
  1601. $driver->fullscreen_window();
  1602. =cut
  1603. sub fullscreen_window {
  1604. my ( $self, $window ) = @_;
  1605. $window = ( defined $window ) ? $window : 'current';
  1606. my $res = { 'command' => 'fullscreenWindow', 'window_handle' => $window };
  1607. my $ret = $self->_execute_command($res);
  1608. return $ret ? 1 : 0;
  1609. }
  1610. =head2 get_all_cookies
  1611. Description:
  1612. Retrieve all cookies visible to the current page. Each cookie will be
  1613. returned as a HASH reference with the following keys & their value types:
  1614. 'name' - STRING
  1615. 'value' - STRING
  1616. 'path' - STRING
  1617. 'domain' - STRING
  1618. 'secure' - BOOLEAN
  1619. Output:
  1620. ARRAY of HASHES - list of all the cookie hashes
  1621. Usage:
  1622. print Dumper($driver->get_all_cookies());
  1623. =cut
  1624. sub get_all_cookies {
  1625. my ($self) = @_;
  1626. my $res = { 'command' => 'getAllCookies' };
  1627. return $self->_execute_command($res);
  1628. }
  1629. =head2 add_cookie
  1630. Description:
  1631. Set a cookie on the domain.
  1632. Input: 2 (4 optional)
  1633. Required:
  1634. 'name' - STRING
  1635. 'value' - STRING
  1636. Optional:
  1637. 'path' - STRING
  1638. 'domain' - STRING
  1639. 'secure' - BOOLEAN - default false.
  1640. 'httponly' - BOOLEAN - default false.
  1641. 'expiry' - TIME_T - default 20 years in the future
  1642. Usage:
  1643. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0, 1)
  1644. =cut
  1645. sub add_cookie {
  1646. my ( $self, $name, $value, $path, $domain, $secure, $httponly, $expiry ) =
  1647. @_;
  1648. if ( ( not defined $name )
  1649. || ( not defined $value ) )
  1650. {
  1651. croak "Missing parameters";
  1652. }
  1653. my $res = { 'command' => 'addCookie' };
  1654. my $json_false = JSON::false;
  1655. my $json_true = JSON::true;
  1656. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1657. my $params = {
  1658. 'cookie' => {
  1659. 'name' => $name,
  1660. 'value' => $value,
  1661. 'path' => $path,
  1662. 'secure' => $secure,
  1663. }
  1664. };
  1665. $params->{cookie}->{domain} = $domain if $domain;
  1666. $params->{cookie}->{'httponly'} = $httponly if $httponly;
  1667. $params->{cookie}->{'expiry'} = $expiry if $expiry;
  1668. return $self->_execute_command( $res, $params );
  1669. }
  1670. =head2 delete_all_cookies
  1671. Description:
  1672. Delete all cookies visible to the current page.
  1673. Usage:
  1674. $driver->delete_all_cookies();
  1675. =cut
  1676. sub delete_all_cookies {
  1677. my ($self) = @_;
  1678. my $res = { 'command' => 'deleteAllCookies' };
  1679. return $self->_execute_command($res);
  1680. }
  1681. =head2 get_cookie_named
  1682. Basically get only the cookie with the provided name.
  1683. Probably preferable to pick it out of the list unless you expect a *really* long list.
  1684. Input:
  1685. Cookie Name - STRING
  1686. Returns cookie definition hash, much like the elements in get_all_cookies();
  1687. Compatibility:
  1688. Only available on webdriver3 enabled selenium servers.
  1689. =cut
  1690. sub get_cookie_named {
  1691. my ( $self, $cookie_name ) = @_;
  1692. my $res = { 'command' => 'getCookieNamed', 'name' => $cookie_name };
  1693. return $self->_execute_command($res);
  1694. }
  1695. =head2 delete_cookie_named
  1696. Description:
  1697. Delete the cookie with the given name. This command will be a no-op if there
  1698. is no such cookie visible to the current page.
  1699. Input: 1
  1700. Required:
  1701. STRING - name of cookie to delete
  1702. Usage:
  1703. $driver->delete_cookie_named('foo');
  1704. =cut
  1705. sub delete_cookie_named {
  1706. my ( $self, $cookie_name ) = @_;
  1707. if ( not defined $cookie_name ) {
  1708. croak "Cookie name not provided";
  1709. }
  1710. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1711. return $self->_execute_command($res);
  1712. }
  1713. =head2 get_page_source
  1714. Description:
  1715. Get the current page source.
  1716. Output:
  1717. STRING - The page source.
  1718. Usage:
  1719. print $driver->get_page_source();
  1720. =cut
  1721. sub get_page_source {
  1722. my ($self) = @_;
  1723. my $res = { 'command' => 'getPageSource' };
  1724. return $self->_execute_command($res);
  1725. }
  1726. =head2 find_element
  1727. Description:
  1728. Search for an element on the page, starting from the document
  1729. root. The located element will be returned as a WebElement
  1730. object. If the element cannot be found, we will CROAK, killing
  1731. your script. If you wish for a warning instead, use the
  1732. parameterized version of the finders:
  1733. find_element_by_class
  1734. find_element_by_class_name
  1735. find_element_by_css
  1736. find_element_by_id
  1737. find_element_by_link
  1738. find_element_by_link_text
  1739. find_element_by_name
  1740. find_element_by_partial_link_text
  1741. find_element_by_tag_name
  1742. find_element_by_xpath
  1743. These functions all take a single STRING argument: the locator
  1744. search target of the element you want. If the element is found, we
  1745. will receive a WebElement. Otherwise, we will return 0. Note that
  1746. invoking methods on 0 will of course kill your script.
  1747. Input: 2 (1 optional)
  1748. Required:
  1749. STRING - The search target.
  1750. Optional:
  1751. STRING - Locator scheme to use to search the element, available schemes:
  1752. {class, class_name, css, id, link, link_text, partial_link_text,
  1753. tag_name, name, xpath}
  1754. Defaults to 'xpath' if not configured global during instantiation.
  1755. Output:
  1756. Selenium::Remote::WebElement - WebElement Object
  1757. (This could be a subclass of L<Selenium::Remote::WebElement> if C<webelement_class> was set.
  1758. Usage:
  1759. $driver->find_element("//input[\@name='q']");
  1760. =cut
  1761. sub find_element {
  1762. my ( $self, $query, $method ) = @_;
  1763. if ( not defined $query ) {
  1764. croak 'Search string to find element not provided.';
  1765. }
  1766. my $res = { 'command' => 'findElement' };
  1767. my $params = $self->_build_find_params( $method, $query );
  1768. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1769. if ($@) {
  1770. if ( $@ =~
  1771. /(An element could not be located on the page using the given search parameters)/
  1772. )
  1773. {
  1774. # give details on what element wasn't found
  1775. $@ = "$1: $query,$params->{using}";
  1776. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1777. croak $@;
  1778. }
  1779. else {
  1780. # re throw if the exception wasn't what we expected
  1781. die $@;
  1782. }
  1783. }
  1784. return $self->webelement_class->new(
  1785. id => $ret_data,
  1786. driver => $self
  1787. );
  1788. }
  1789. =head2 find_elements
  1790. Description:
  1791. Search for multiple elements on the page, starting from the document root.
  1792. The located elements will be returned as an array of WebElement object.
  1793. Input: 2 (1 optional)
  1794. Required:
  1795. STRING - The search target.
  1796. Optional:
  1797. STRING - Locator scheme to use to search the element, available schemes:
  1798. {class, class_name, css, id, link, link_text, partial_link_text,
  1799. tag_name, name, xpath}
  1800. Defaults to 'xpath' if not configured global during instantiation.
  1801. Output:
  1802. ARRAY or ARRAYREF of WebElement Objects
  1803. Usage:
  1804. $driver->find_elements("//input");
  1805. =cut
  1806. sub find_elements {
  1807. my ( $self, $query, $method ) = @_;
  1808. if ( not defined $query ) {
  1809. croak 'Search string to find element not provided.';
  1810. }
  1811. my $res = { 'command' => 'findElements' };
  1812. my $params = $self->_build_find_params( $method, $query );
  1813. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1814. if ($@) {
  1815. if ( $@ =~
  1816. /(An element could not be located on the page using the given search parameters)/
  1817. )
  1818. {
  1819. # give details on what element wasn't found
  1820. $@ = "$1: $query,$params->{using}";
  1821. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1822. croak $@;
  1823. }
  1824. else {
  1825. # re throw if the exception wasn't what we expected
  1826. die $@;
  1827. }
  1828. }
  1829. my $elem_obj_arr = [];
  1830. foreach (@$ret_data) {
  1831. push(
  1832. @$elem_obj_arr,
  1833. $self->webelement_class->new(
  1834. id => $_,
  1835. driver => $self
  1836. )
  1837. );
  1838. }
  1839. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1840. }
  1841. =head2 find_child_element
  1842. Description:
  1843. Search for an element on the page, starting from the identified element. The
  1844. located element will be returned as a WebElement object.
  1845. Input: 3 (1 optional)
  1846. Required:
  1847. Selenium::Remote::WebElement - WebElement object from where you want to
  1848. start searching.
  1849. STRING - The search target. (Do not use a double whack('//')
  1850. in an xpath to search for a child element
  1851. ex: '//option[@id="something"]'
  1852. instead use a dot whack ('./')
  1853. ex: './option[@id="something"]')
  1854. Optional:
  1855. STRING - Locator scheme to use to search the element, available schemes:
  1856. {class, class_name, css, id, link, link_text, partial_link_text,
  1857. tag_name, name, xpath}
  1858. Defaults to 'xpath' if not configured global during instantiation.
  1859. Output:
  1860. WebElement Object
  1861. Usage:
  1862. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1863. # note the usage of ./ when searching for a child element instead of //
  1864. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1865. =cut
  1866. sub find_child_element {
  1867. my ( $self, $elem, $query, $method ) = @_;
  1868. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1869. croak "Missing parameters";
  1870. }
  1871. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1872. my $params = $self->_build_find_params( $method, $query );
  1873. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1874. if ($@) {
  1875. if ( $@ =~
  1876. /(An element could not be located on the page using the given search parameters)/
  1877. )
  1878. {
  1879. # give details on what element wasn't found
  1880. $@ = "$1: $query,$params->{using}";
  1881. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1882. croak $@;
  1883. }
  1884. else {
  1885. # re throw if the exception wasn't what we expected
  1886. die $@;
  1887. }
  1888. }
  1889. return $self->webelement_class->new(
  1890. id => $ret_data,
  1891. driver => $self
  1892. );
  1893. }
  1894. =head2 find_child_elements
  1895. Description:
  1896. Search for multiple element on the page, starting from the identified
  1897. element. The located elements will be returned as an array of WebElement
  1898. objects.
  1899. Input: 3 (1 optional)
  1900. Required:
  1901. Selenium::Remote::WebElement - WebElement object from where you want to
  1902. start searching.
  1903. STRING - The search target.
  1904. Optional:
  1905. STRING - Locator scheme to use to search the element, available schemes:
  1906. {class, class_name, css, id, link, link_text, partial_link_text,
  1907. tag_name, name, xpath}
  1908. Defaults to 'xpath' if not configured global during instantiation.
  1909. Output:
  1910. ARRAY of WebElement Objects.
  1911. Usage:
  1912. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1913. # note the usage of ./ when searching for a child element instead of //
  1914. my $child = $driver->find_child_elements($elem1, "./option");
  1915. =cut
  1916. sub find_child_elements {
  1917. my ( $self, $elem, $query, $method ) = @_;
  1918. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1919. croak "Missing parameters";
  1920. }
  1921. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1922. my $params = $self->_build_find_params( $method, $query );
  1923. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1924. if ($@) {
  1925. if ( $@ =~
  1926. /(An element could not be located on the page using the given search parameters)/
  1927. )
  1928. {
  1929. # give details on what element wasn't found
  1930. $@ = "$1: $query,$params->{using}";
  1931. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1932. croak $@;
  1933. }
  1934. else {
  1935. # re throw if the exception wasn't what we expected
  1936. die $@;
  1937. }
  1938. }
  1939. my $elem_obj_arr = [];
  1940. my $i = 0;
  1941. foreach (@$ret_data) {
  1942. $elem_obj_arr->[$i] = $self->webelement_class->new(
  1943. id => $_,
  1944. driver => $self
  1945. );
  1946. $i++;
  1947. }
  1948. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1949. }
  1950. =head2 find_element_by_class
  1951. See L</find_element>.
  1952. =head2 find_element_by_class_name
  1953. See L</find_element>.
  1954. =head2 find_element_by_css
  1955. See L</find_element>.
  1956. =head2 find_element_by_id
  1957. See L</find_element>.
  1958. =head2 find_element_by_link
  1959. See L</find_element>.
  1960. =head2 find_element_by_link_text
  1961. See L</find_element>.
  1962. =head2 find_element_by_name
  1963. See L</find_element>.
  1964. =head2 find_element_by_partial_link_text
  1965. See L</find_element>.
  1966. =head2 find_element_by_tag_name
  1967. See L</find_element>.
  1968. =head2 find_element_by_xpath
  1969. See L</find_element>.
  1970. =head2 get_active_element
  1971. Description:
  1972. Get the element on the page that currently has focus.. The located element
  1973. will be returned as a WebElement object.
  1974. Output:
  1975. WebElement Object
  1976. Usage:
  1977. $driver->get_active_element();
  1978. =cut
  1979. sub _build_find_params {
  1980. my ( $self, $method, $query ) = @_;
  1981. my $using = $self->_build_using($method);
  1982. # geckodriver doesn't accept name as a valid selector
  1983. if ( $self->isa('Selenium::Firefox') && $using eq 'name' ) {
  1984. return {
  1985. using => 'css selector',
  1986. value => qq{[name="$query"]}
  1987. };
  1988. }
  1989. else {
  1990. return {
  1991. using => $using,
  1992. value => $query
  1993. };
  1994. }
  1995. }
  1996. sub _build_using {
  1997. my ( $self, $method ) = @_;
  1998. if ($method) {
  1999. if ( $self->FINDERS->{$method} ) {
  2000. return $self->FINDERS->{$method};
  2001. }
  2002. else {
  2003. croak 'Bad method, expected: '
  2004. . join( ', ', keys %{ $self->FINDERS } )
  2005. . ", got $method";
  2006. }
  2007. }
  2008. else {
  2009. return $self->default_finder;
  2010. }
  2011. }
  2012. sub get_active_element {
  2013. my ($self) = @_;
  2014. my $res = { 'command' => 'getActiveElement' };
  2015. my $ret_data = eval { $self->_execute_command($res) };
  2016. if ($@) {
  2017. croak $@;
  2018. }
  2019. else {
  2020. return $self->webelement_class->new(
  2021. id => $ret_data,
  2022. driver => $self
  2023. );
  2024. }
  2025. }
  2026. =head2 cache_status
  2027. Description:
  2028. Get the status of the html5 application cache.
  2029. Usage:
  2030. print $driver->cache_status;
  2031. Output:
  2032. <number> - Status code for application cache: {UNCACHED = 0, IDLE = 1, CHECKING = 2, DOWNLOADING = 3, UPDATE_READY = 4, OBSOLETE = 5}
  2033. =cut
  2034. sub cache_status {
  2035. my ($self) = @_;
  2036. my $res = { 'command' => 'cacheStatus' };
  2037. return $self->_execute_command($res);
  2038. }
  2039. =head2 set_geolocation
  2040. Description:
  2041. Set the current geographic location - note that your driver must
  2042. implement this endpoint, or else it will crash your session. At the
  2043. very least, it works in v2.12 of Chromedriver.
  2044. Input:
  2045. Required:
  2046. HASH: A hash with key C<location> whose value is a Location hashref. See
  2047. usage section for example.
  2048. Usage:
  2049. $driver->set_geolocation( location => {
  2050. latitude => 40.714353,
  2051. longitude => -74.005973,
  2052. altitude => 0.056747
  2053. });
  2054. Output:
  2055. BOOLEAN - success or failure
  2056. =cut
  2057. sub set_geolocation {
  2058. my ( $self, %params ) = @_;
  2059. my $res = { 'command' => 'setGeolocation' };
  2060. return $self->_execute_command( $res, \%params );
  2061. }
  2062. =head2 get_geolocation
  2063. Description:
  2064. Get the current geographic location. Note that your webdriver must
  2065. implement this endpoint - otherwise, it will crash your session. At
  2066. the time of release, we couldn't get this to work on the desktop
  2067. FirefoxDriver or desktop Chromedriver.
  2068. Usage:
  2069. print $driver->get_geolocation;
  2070. Output:
  2071. { latitude: number, longitude: number, altitude: number } - The current geo location.
  2072. =cut
  2073. sub get_geolocation {
  2074. my ($self) = @_;
  2075. my $res = { 'command' => 'getGeolocation' };
  2076. return $self->_execute_command($res);
  2077. }
  2078. =head2 get_log
  2079. Description:
  2080. Get the log for a given log type. Log buffer is reset after each request.
  2081. Input:
  2082. Required:
  2083. <STRING> - Type of log to retrieve:
  2084. {client|driver|browser|server}. There may be others available; see
  2085. get_log_types for a full list for your driver.
  2086. Usage:
  2087. $driver->get_log( $log_type );
  2088. Output:
  2089. <ARRAY|ARRAYREF> - An array of log entries since the most recent request.
  2090. =cut
  2091. sub get_log {
  2092. my ( $self, $type ) = @_;
  2093. my $res = { 'command' => 'getLog' };
  2094. return $self->_execute_command( $res, { type => $type } );
  2095. }
  2096. =head2 get_log_types
  2097. Description:
  2098. Get available log types. By default, every driver should have client,
  2099. driver, browser, and server types, but there may be more available,
  2100. depending on your driver.
  2101. Usage:
  2102. my @types = $driver->get_log_types;
  2103. $driver->get_log($types[0]);
  2104. Output:
  2105. <ARRAYREF> - The list of log types.
  2106. =cut
  2107. sub get_log_types {
  2108. my ($self) = @_;
  2109. my $res = { 'command' => 'getLogTypes' };
  2110. return $self->_execute_command($res);
  2111. }
  2112. =head2 set_orientation
  2113. Description:
  2114. Set the browser orientation.
  2115. Input:
  2116. Required:
  2117. <STRING> - Orientation {LANDSCAPE|PORTRAIT}
  2118. Usage:
  2119. $driver->set_orientation( $orientation );
  2120. Output:
  2121. BOOLEAN - success or failure
  2122. =cut
  2123. sub set_orientation {
  2124. my ( $self, $orientation ) = @_;
  2125. my $res = { 'command' => 'setOrientation' };
  2126. return $self->_execute_command( $res, { orientation => $orientation } );
  2127. }
  2128. =head2 get_orientation
  2129. Description:
  2130. Get the current browser orientation. Returns either LANDSCAPE|PORTRAIT.
  2131. Usage:
  2132. print $driver->get_orientation;
  2133. Output:
  2134. <STRING> - your orientation.
  2135. =cut
  2136. sub get_orientation {
  2137. my ($self) = @_;
  2138. my $res = { 'command' => 'getOrientation' };
  2139. return $self->_execute_command($res);
  2140. }
  2141. =head2 send_modifier
  2142. Description:
  2143. Send an event to the active element to depress or release a modifier key.
  2144. Input: 2
  2145. Required:
  2146. 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
  2147. isdown - Boolean/String - Whether to generate a key down or key up
  2148. Usage:
  2149. $driver->send_modifier('Alt','down');
  2150. $elem->send_keys('c');
  2151. $driver->send_modifier('Alt','up');
  2152. or
  2153. $driver->send_modifier('Alt',1);
  2154. $elem->send_keys('c');
  2155. $driver->send_modifier('Alt',0);
  2156. =cut
  2157. sub send_modifier {
  2158. my ( $self, $modifier, $isdown ) = @_;
  2159. if ( $isdown =~ /(down|up)/ ) {
  2160. $isdown = $isdown =~ /down/ ? 1 : 0;
  2161. }
  2162. if ( $self->{is_wd3}
  2163. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2164. {
  2165. my $acts = [
  2166. {
  2167. type => $isdown ? 'keyDown' : 'keyUp',
  2168. value => KEYS->{ lc($modifier) },
  2169. },
  2170. ];
  2171. my $action = {
  2172. actions => [
  2173. {
  2174. id => 'key',
  2175. type => 'key',
  2176. actions => $acts,
  2177. }
  2178. ]
  2179. };
  2180. _queue_action(%$action);
  2181. return 1;
  2182. }
  2183. my $res = { 'command' => 'sendModifier' };
  2184. my $params = {
  2185. value => $modifier,
  2186. isdown => $isdown
  2187. };
  2188. return $self->_execute_command( $res, $params );
  2189. }
  2190. =head2 compare_elements
  2191. Description:
  2192. Test if two element IDs refer to the same DOM element.
  2193. Input: 2
  2194. Required:
  2195. Selenium::Remote::WebElement - WebElement Object
  2196. Selenium::Remote::WebElement - WebElement Object
  2197. Output:
  2198. BOOLEAN
  2199. Usage:
  2200. $driver->compare_elements($elem_obj1, $elem_obj2);
  2201. =cut
  2202. sub compare_elements {
  2203. my ( $self, $elem1, $elem2 ) = @_;
  2204. my $res = {
  2205. 'command' => 'elementEquals',
  2206. 'id' => $elem1->{id},
  2207. 'other' => $elem2->{id}
  2208. };
  2209. return $self->_execute_command($res);
  2210. }
  2211. =head2 click
  2212. Description:
  2213. Click any mouse button (at the coordinates set by the last moveto command).
  2214. Input:
  2215. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  2216. defaults to 'LEFT'
  2217. queue - (optional) queue the click, rather than executing it. WD3 only.
  2218. Usage:
  2219. $driver->click('LEFT');
  2220. $driver->click(1); #MIDDLE
  2221. $driver->click('RIGHT');
  2222. $driver->click; #Defaults to left
  2223. =cut
  2224. sub click {
  2225. my ( $self, $button, $append ) = @_;
  2226. $button = _get_button($button);
  2227. my $res = { 'command' => 'click' };
  2228. my $params = { 'button' => $button };
  2229. if ( $self->{is_wd3}
  2230. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2231. {
  2232. $params = {
  2233. actions => [
  2234. {
  2235. type => "pointer",
  2236. id => 'mouse',
  2237. parameters => { "pointerType" => "mouse" },
  2238. actions => [
  2239. {
  2240. type => "pointerDown",
  2241. duration => 0,
  2242. button => $button,
  2243. },
  2244. {
  2245. type => "pointerUp",
  2246. duration => 0,
  2247. button => $button,
  2248. },
  2249. ],
  2250. }
  2251. ],
  2252. };
  2253. if ($append) {
  2254. _queue_action(%$params);
  2255. return 1;
  2256. }
  2257. return $self->general_action(%$params);
  2258. }
  2259. return $self->_execute_command( $res, $params );
  2260. }
  2261. sub _get_button {
  2262. my $button = shift;
  2263. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  2264. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  2265. return $button_enum->{ uc $1 };
  2266. }
  2267. if ( defined $button && $button =~ /(0|1|2)/ ) {
  2268. #Handle user error sending in "1"
  2269. return int($1);
  2270. }
  2271. return 0;
  2272. }
  2273. =head2 double_click
  2274. Description:
  2275. Double-clicks at the current mouse coordinates (set by moveto).
  2276. Compatibility:
  2277. On webdriver3 enabled servers, you can double click arbitrary mouse buttons.
  2278. Usage:
  2279. $driver->double_click(button);
  2280. =cut
  2281. sub double_click {
  2282. my ( $self, $button ) = @_;
  2283. $button = _get_button($button);
  2284. if ( $self->{is_wd3}
  2285. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2286. {
  2287. $self->click( $button, 1 );
  2288. $self->click( $button, 1 );
  2289. return $self->general_action();
  2290. }
  2291. my $res = { 'command' => 'doubleClick' };
  2292. return $self->_execute_command($res);
  2293. }
  2294. =head2 button_down
  2295. Description:
  2296. Click and hold the left mouse button (at the coordinates set by the
  2297. last moveto command). Note that the next mouse-related command that
  2298. should follow is buttonup . Any other mouse command (such as click
  2299. or another call to buttondown) will yield undefined behaviour.
  2300. Compatibility:
  2301. On WebDriver 3 enabled servers, all this does is queue a button down action.
  2302. You will either have to call general_action() to perform the queue, or an action like click() which also clears the queue.
  2303. Usage:
  2304. $self->button_down;
  2305. =cut
  2306. sub button_down {
  2307. my ($self) = @_;
  2308. if ( $self->{is_wd3}
  2309. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2310. {
  2311. my $params = {
  2312. actions => [
  2313. {
  2314. type => "pointer",
  2315. id => 'mouse',
  2316. parameters => { "pointerType" => "mouse" },
  2317. actions => [
  2318. {
  2319. type => "pointerDown",
  2320. duration => 0,
  2321. button => 0,
  2322. },
  2323. ],
  2324. }
  2325. ],
  2326. };
  2327. _queue_action(%$params);
  2328. return 1;
  2329. }
  2330. my $res = { 'command' => 'buttonDown' };
  2331. return $self->_execute_command($res);
  2332. }
  2333. =head2 button_up
  2334. Description:
  2335. Releases the mouse button previously held (where the mouse is
  2336. currently at). Must be called once for every buttondown command
  2337. issued. See the note in click and buttondown about implications of
  2338. out-of-order commands.
  2339. Compatibility:
  2340. On WebDriver 3 enabled servers, all this does is queue a button down action.
  2341. You will either have to call general_action() to perform the queue, or an action like click() which also clears the queue.
  2342. Usage:
  2343. $self->button_up;
  2344. =cut
  2345. sub button_up {
  2346. my ($self) = @_;
  2347. if ( $self->{is_wd3}
  2348. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2349. {
  2350. my $params = {
  2351. actions => [
  2352. {
  2353. type => "pointer",
  2354. id => 'mouse',
  2355. parameters => { "pointerType" => "mouse" },
  2356. actions => [
  2357. {
  2358. type => "pointerDown",
  2359. duration => 0,
  2360. button => 0,
  2361. },
  2362. ],
  2363. }
  2364. ],
  2365. };
  2366. _queue_action(%$params);
  2367. return 1;
  2368. }
  2369. my $res = { 'command' => 'buttonUp' };
  2370. return $self->_execute_command($res);
  2371. }
  2372. =head2 upload_file
  2373. Description:
  2374. Upload a file from the local machine to the selenium server
  2375. machine. That file then can be used for testing file upload on web
  2376. forms. Returns the remote-server's path to the file.
  2377. Passing raw data as an argument past the filename will upload
  2378. that rather than the file's contents.
  2379. When passing raw data, be advised that it expects a zipped
  2380. and then base64 encoded version of a single file.
  2381. Multiple files and/or directories are not supported by the remote server.
  2382. Usage:
  2383. my $remote_fname = $driver->upload_file( $fname );
  2384. my $element = $driver->find_element( '//input[@id="file"]' );
  2385. $element->send_keys( $remote_fname );
  2386. =cut
  2387. # this method duplicates upload() method in the
  2388. # org.openqa.selenium.remote.RemoteWebElement java class.
  2389. sub upload_file {
  2390. my ( $self, $filename, $raw_content ) = @_;
  2391. my $params;
  2392. if ( defined $raw_content ) {
  2393. #If no processing is passed, send the argument raw
  2394. $params = { file => $raw_content };
  2395. }
  2396. else {
  2397. #Otherwise, zip/base64 it.
  2398. $params = $self->_prepare_file($filename);
  2399. }
  2400. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  2401. my $ret = $self->_execute_command( $res, $params );
  2402. return $ret;
  2403. }
  2404. sub _prepare_file {
  2405. my ( $self, $filename ) = @_;
  2406. if ( not -r $filename ) { croak "upload_file: no such file: $filename"; }
  2407. my $string = ""; # buffer
  2408. my $zip = Archive::Zip->new();
  2409. $zip->addFile( $filename, basename($filename) );
  2410. if ( $zip->writeToFileHandle( IO::String->new($string) ) != AZ_OK ) {
  2411. die 'zip failed';
  2412. }
  2413. return { file => MIME::Base64::encode_base64( $string, '' ) };
  2414. }
  2415. =head2 get_text
  2416. Description:
  2417. Get the text of a particular element. Wrapper around L</find_element>
  2418. Usage:
  2419. $text = $driver->get_text("//div[\@name='q']");
  2420. =cut
  2421. sub get_text {
  2422. my $self = shift;
  2423. return $self->find_element(@_)->get_text();
  2424. }
  2425. =head2 get_body
  2426. Description:
  2427. Get the current text for the whole body. If you want the entire raw HTML instead,
  2428. See L</get_page_source>.
  2429. Usage:
  2430. $body_text = $driver->get_body();
  2431. =cut
  2432. sub get_body {
  2433. my $self = shift;
  2434. return $self->get_text( '//body', 'xpath' );
  2435. }
  2436. =head2 get_path
  2437. Description:
  2438. Get the path part of the current browser location.
  2439. Usage:
  2440. $path = $driver->get_path();
  2441. =cut
  2442. sub get_path {
  2443. my $self = shift;
  2444. my $location = $self->get_current_url;
  2445. $location =~ s/\?.*//; # strip of query params
  2446. $location =~ s/#.*//; # strip of anchors
  2447. $location =~ s#^https?://[^/]+##; # strip off host
  2448. return $location;
  2449. }
  2450. =head2 get_user_agent
  2451. Description:
  2452. Convenience method to get the user agent string, according to the
  2453. browser's value for window.navigator.userAgent.
  2454. Usage:
  2455. $user_agent = $driver->get_user_agent()
  2456. =cut
  2457. sub get_user_agent {
  2458. my $self = shift;
  2459. return $self->execute_script('return window.navigator.userAgent;');
  2460. }
  2461. =head2 set_inner_window_size
  2462. Description:
  2463. Set the inner window size by closing the current window and
  2464. reopening the current page in a new window. This can be useful
  2465. when using browsers to mock as mobile devices.
  2466. This sub will be fired automatically if you set the
  2467. C<inner_window_size> hash key option during instantiation.
  2468. Input:
  2469. INT - height of the window
  2470. INT - width of the window
  2471. Output:
  2472. BOOLEAN - Success or failure
  2473. Usage:
  2474. $driver->set_inner_window_size(640, 480)
  2475. =cut
  2476. sub set_inner_window_size {
  2477. my $self = shift;
  2478. my $height = shift;
  2479. my $width = shift;
  2480. my $location = $self->get_current_url;
  2481. $self->execute_script( 'window.open("' . $location . '", "_blank")' );
  2482. $self->close;
  2483. my @handles = @{ $self->get_window_handles };
  2484. $self->switch_to_window( pop @handles );
  2485. my @resize = (
  2486. 'window.innerHeight = ' . $height,
  2487. 'window.innerWidth = ' . $width,
  2488. 'return 1'
  2489. );
  2490. return $self->execute_script( join( ';', @resize ) ) ? 1 : 0;
  2491. }
  2492. =head2 get_local_storage_item
  2493. Description:
  2494. Get the value of a local storage item specified by the given key.
  2495. Input: 1
  2496. Required:
  2497. STRING - name of the key to be retrieved
  2498. Output:
  2499. STRING - value of the local storage item
  2500. Usage:
  2501. $driver->get_local_storage_item('key')
  2502. =cut
  2503. sub get_local_storage_item {
  2504. my ( $self, $key ) = @_;
  2505. my $res = { 'command' => 'getLocalStorageItem' };
  2506. my $params = { 'key' => $key };
  2507. return $self->_execute_command( $res, $params );
  2508. }
  2509. =head2 delete_local_storage_item
  2510. Description:
  2511. Get the value of a local storage item specified by the given key.
  2512. Input: 1
  2513. Required
  2514. STRING - name of the key to be deleted
  2515. Usage:
  2516. $driver->delete_local_storage_item('key')
  2517. =cut
  2518. sub delete_local_storage_item {
  2519. my ( $self, $key ) = @_;
  2520. my $res = { 'command' => 'deleteLocalStorageItem' };
  2521. my $params = { 'key' => $key };
  2522. return $self->_execute_command( $res, $params );
  2523. }
  2524. sub _coerce_timeout_ms {
  2525. my ($ms) = @_;
  2526. if ( defined $ms ) {
  2527. return _coerce_number($ms);
  2528. }
  2529. else {
  2530. croak 'Expecting a timeout in ms';
  2531. }
  2532. }
  2533. sub _coerce_number {
  2534. my ($maybe_number) = @_;
  2535. if ( Scalar::Util::looks_like_number($maybe_number) ) {
  2536. return $maybe_number + 0;
  2537. }
  2538. else {
  2539. croak "Expecting a number, not: $maybe_number";
  2540. }
  2541. }
  2542. 1;