electron_api_web_contents.cc 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499
  1. // Copyright (c) 2014 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/api/electron_api_web_contents.h"
  5. #include <limits>
  6. #include <memory>
  7. #include <set>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/containers/contains.h"
  12. #include "base/containers/fixed_flat_map.h"
  13. #include "base/containers/id_map.h"
  14. #include "base/files/file_util.h"
  15. #include "base/json/json_reader.h"
  16. #include "base/no_destructor.h"
  17. #include "base/strings/utf_string_conversions.h"
  18. #include "base/task/current_thread.h"
  19. #include "base/task/thread_pool.h"
  20. #include "base/threading/scoped_blocking_call.h"
  21. #include "base/values.h"
  22. #include "chrome/browser/browser_process.h"
  23. #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
  24. #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
  25. #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
  26. #include "chrome/common/pref_names.h"
  27. #include "components/embedder_support/user_agent_utils.h"
  28. #include "components/prefs/pref_service.h"
  29. #include "components/prefs/scoped_user_pref_update.h"
  30. #include "components/security_state/content/content_utils.h"
  31. #include "components/security_state/core/security_state.h"
  32. #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
  33. #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
  34. #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
  35. #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
  36. #include "content/public/browser/child_process_security_policy.h"
  37. #include "content/public/browser/context_menu_params.h"
  38. #include "content/public/browser/desktop_media_id.h"
  39. #include "content/public/browser/desktop_streams_registry.h"
  40. #include "content/public/browser/download_request_utils.h"
  41. #include "content/public/browser/favicon_status.h"
  42. #include "content/public/browser/file_select_listener.h"
  43. #include "content/public/browser/native_web_keyboard_event.h"
  44. #include "content/public/browser/navigation_details.h"
  45. #include "content/public/browser/navigation_entry.h"
  46. #include "content/public/browser/navigation_handle.h"
  47. #include "content/public/browser/render_frame_host.h"
  48. #include "content/public/browser/render_process_host.h"
  49. #include "content/public/browser/render_view_host.h"
  50. #include "content/public/browser/render_widget_host.h"
  51. #include "content/public/browser/render_widget_host_view.h"
  52. #include "content/public/browser/service_worker_context.h"
  53. #include "content/public/browser/site_instance.h"
  54. #include "content/public/browser/storage_partition.h"
  55. #include "content/public/browser/web_contents.h"
  56. #include "content/public/common/referrer_type_converters.h"
  57. #include "content/public/common/result_codes.h"
  58. #include "content/public/common/webplugininfo.h"
  59. #include "electron/buildflags/buildflags.h"
  60. #include "electron/shell/common/api/api.mojom.h"
  61. #include "gin/arguments.h"
  62. #include "gin/data_object_builder.h"
  63. #include "gin/handle.h"
  64. #include "gin/object_template_builder.h"
  65. #include "gin/wrappable.h"
  66. #include "media/base/mime_util.h"
  67. #include "mojo/public/cpp/bindings/associated_remote.h"
  68. #include "mojo/public/cpp/bindings/pending_receiver.h"
  69. #include "mojo/public/cpp/bindings/remote.h"
  70. #include "mojo/public/cpp/system/platform_handle.h"
  71. #include "ppapi/buildflags/buildflags.h"
  72. #include "printing/buildflags/buildflags.h"
  73. #include "printing/print_job_constants.h"
  74. #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
  75. #include "services/service_manager/public/cpp/interface_provider.h"
  76. #include "shell/browser/api/electron_api_browser_window.h"
  77. #include "shell/browser/api/electron_api_debugger.h"
  78. #include "shell/browser/api/electron_api_session.h"
  79. #include "shell/browser/api/electron_api_web_frame_main.h"
  80. #include "shell/browser/api/message_port.h"
  81. #include "shell/browser/browser.h"
  82. #include "shell/browser/child_web_contents_tracker.h"
  83. #include "shell/browser/electron_autofill_driver_factory.h"
  84. #include "shell/browser/electron_browser_client.h"
  85. #include "shell/browser/electron_browser_context.h"
  86. #include "shell/browser/electron_browser_main_parts.h"
  87. #include "shell/browser/electron_javascript_dialog_manager.h"
  88. #include "shell/browser/electron_navigation_throttle.h"
  89. #include "shell/browser/file_select_helper.h"
  90. #include "shell/browser/native_window.h"
  91. #include "shell/browser/osr/osr_render_widget_host_view.h"
  92. #include "shell/browser/osr/osr_web_contents_view.h"
  93. #include "shell/browser/session_preferences.h"
  94. #include "shell/browser/ui/drag_util.h"
  95. #include "shell/browser/ui/file_dialog.h"
  96. #include "shell/browser/ui/inspectable_web_contents.h"
  97. #include "shell/browser/ui/inspectable_web_contents_view.h"
  98. #include "shell/browser/web_contents_permission_helper.h"
  99. #include "shell/browser/web_contents_preferences.h"
  100. #include "shell/browser/web_contents_zoom_controller.h"
  101. #include "shell/browser/web_view_guest_delegate.h"
  102. #include "shell/browser/web_view_manager.h"
  103. #include "shell/common/api/electron_api_native_image.h"
  104. #include "shell/common/api/electron_bindings.h"
  105. #include "shell/common/color_util.h"
  106. #include "shell/common/electron_constants.h"
  107. #include "shell/common/gin_converters/base_converter.h"
  108. #include "shell/common/gin_converters/blink_converter.h"
  109. #include "shell/common/gin_converters/callback_converter.h"
  110. #include "shell/common/gin_converters/content_converter.h"
  111. #include "shell/common/gin_converters/file_path_converter.h"
  112. #include "shell/common/gin_converters/frame_converter.h"
  113. #include "shell/common/gin_converters/gfx_converter.h"
  114. #include "shell/common/gin_converters/gurl_converter.h"
  115. #include "shell/common/gin_converters/image_converter.h"
  116. #include "shell/common/gin_converters/net_converter.h"
  117. #include "shell/common/gin_converters/optional_converter.h"
  118. #include "shell/common/gin_converters/value_converter.h"
  119. #include "shell/common/gin_helper/dictionary.h"
  120. #include "shell/common/gin_helper/object_template_builder.h"
  121. #include "shell/common/language_util.h"
  122. #include "shell/common/node_includes.h"
  123. #include "shell/common/options_switches.h"
  124. #include "shell/common/process_util.h"
  125. #include "shell/common/thread_restrictions.h"
  126. #include "shell/common/v8_value_serializer.h"
  127. #include "storage/browser/file_system/isolated_context.h"
  128. #include "third_party/abseil-cpp/absl/types/optional.h"
  129. #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
  130. #include "third_party/blink/public/common/input/web_input_event.h"
  131. #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
  132. #include "third_party/blink/public/common/page/page_zoom.h"
  133. #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
  134. #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
  135. #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
  136. #include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
  137. #include "ui/base/cursor/cursor.h"
  138. #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
  139. #include "ui/display/screen.h"
  140. #include "ui/events/base_event_utils.h"
  141. #if BUILDFLAG(IS_WIN)
  142. #include "shell/browser/native_window_views.h"
  143. #endif
  144. #if !BUILDFLAG(IS_MAC)
  145. #include "ui/aura/window.h"
  146. #else
  147. #include "ui/base/cocoa/defaults_utils.h"
  148. #endif
  149. #if BUILDFLAG(IS_LINUX)
  150. #include "ui/linux/linux_ui.h"
  151. #endif
  152. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
  153. #include "ui/gfx/font_render_params.h"
  154. #endif
  155. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  156. #include "extensions/browser/script_executor.h"
  157. #include "extensions/browser/view_type_utils.h"
  158. #include "extensions/common/mojom/view_type.mojom.h"
  159. #include "shell/browser/extensions/electron_extension_web_contents_observer.h"
  160. #endif
  161. #if BUILDFLAG(ENABLE_PRINTING)
  162. #include "chrome/browser/printing/print_view_manager_base.h"
  163. #include "components/printing/browser/print_manager_utils.h"
  164. #include "components/printing/browser/print_to_pdf/pdf_print_result.h"
  165. #include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
  166. #include "printing/backend/print_backend.h" // nogncheck
  167. #include "printing/mojom/print.mojom.h" // nogncheck
  168. #include "printing/page_range.h"
  169. #include "shell/browser/printing/print_view_manager_electron.h"
  170. #if BUILDFLAG(IS_WIN)
  171. #include "printing/backend/win_helper.h"
  172. #endif
  173. #endif // BUILDFLAG(ENABLE_PRINTING)
  174. #if BUILDFLAG(ENABLE_PDF_VIEWER)
  175. #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
  176. #include "shell/browser/electron_pdf_web_contents_helper_client.h"
  177. #endif
  178. #if BUILDFLAG(ENABLE_PLUGINS)
  179. #include "content/public/browser/plugin_service.h"
  180. #endif
  181. #if !IS_MAS_BUILD()
  182. #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
  183. #endif
  184. namespace gin {
  185. #if BUILDFLAG(ENABLE_PRINTING)
  186. template <>
  187. struct Converter<printing::mojom::MarginType> {
  188. static bool FromV8(v8::Isolate* isolate,
  189. v8::Local<v8::Value> val,
  190. printing::mojom::MarginType* out) {
  191. using Val = printing::mojom::MarginType;
  192. static constexpr auto Lookup =
  193. base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
  194. {"custom", Val::kCustomMargins},
  195. {"default", Val::kDefaultMargins},
  196. {"none", Val::kNoMargins},
  197. {"printableArea", Val::kPrintableAreaMargins},
  198. });
  199. return FromV8WithLookup(isolate, val, Lookup, out);
  200. }
  201. };
  202. template <>
  203. struct Converter<printing::mojom::DuplexMode> {
  204. static bool FromV8(v8::Isolate* isolate,
  205. v8::Local<v8::Value> val,
  206. printing::mojom::DuplexMode* out) {
  207. using Val = printing::mojom::DuplexMode;
  208. static constexpr auto Lookup =
  209. base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
  210. {"longEdge", Val::kLongEdge},
  211. {"shortEdge", Val::kShortEdge},
  212. {"simplex", Val::kSimplex},
  213. });
  214. return FromV8WithLookup(isolate, val, Lookup, out);
  215. }
  216. };
  217. #endif
  218. template <>
  219. struct Converter<WindowOpenDisposition> {
  220. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  221. WindowOpenDisposition val) {
  222. std::string disposition = "other";
  223. switch (val) {
  224. case WindowOpenDisposition::CURRENT_TAB:
  225. disposition = "default";
  226. break;
  227. case WindowOpenDisposition::NEW_FOREGROUND_TAB:
  228. disposition = "foreground-tab";
  229. break;
  230. case WindowOpenDisposition::NEW_BACKGROUND_TAB:
  231. disposition = "background-tab";
  232. break;
  233. case WindowOpenDisposition::NEW_POPUP:
  234. case WindowOpenDisposition::NEW_WINDOW:
  235. disposition = "new-window";
  236. break;
  237. case WindowOpenDisposition::SAVE_TO_DISK:
  238. disposition = "save-to-disk";
  239. break;
  240. default:
  241. break;
  242. }
  243. return gin::ConvertToV8(isolate, disposition);
  244. }
  245. };
  246. template <>
  247. struct Converter<content::SavePageType> {
  248. static bool FromV8(v8::Isolate* isolate,
  249. v8::Local<v8::Value> val,
  250. content::SavePageType* out) {
  251. using Val = content::SavePageType;
  252. static constexpr auto Lookup =
  253. base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
  254. {"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
  255. {"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
  256. {"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
  257. });
  258. return FromV8WithLowerLookup(isolate, val, Lookup, out);
  259. }
  260. };
  261. template <>
  262. struct Converter<electron::api::WebContents::Type> {
  263. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  264. electron::api::WebContents::Type val) {
  265. using Type = electron::api::WebContents::Type;
  266. std::string type;
  267. switch (val) {
  268. case Type::kBackgroundPage:
  269. type = "backgroundPage";
  270. break;
  271. case Type::kBrowserWindow:
  272. type = "window";
  273. break;
  274. case Type::kBrowserView:
  275. type = "browserView";
  276. break;
  277. case Type::kRemote:
  278. type = "remote";
  279. break;
  280. case Type::kWebView:
  281. type = "webview";
  282. break;
  283. case Type::kOffScreen:
  284. type = "offscreen";
  285. break;
  286. default:
  287. break;
  288. }
  289. return gin::ConvertToV8(isolate, type);
  290. }
  291. static bool FromV8(v8::Isolate* isolate,
  292. v8::Local<v8::Value> val,
  293. electron::api::WebContents::Type* out) {
  294. using Val = electron::api::WebContents::Type;
  295. static constexpr auto Lookup =
  296. base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
  297. {"backgroundPage", Val::kBackgroundPage},
  298. {"browserView", Val::kBrowserView},
  299. {"offscreen", Val::kOffScreen},
  300. {"webview", Val::kWebView},
  301. });
  302. return FromV8WithLookup(isolate, val, Lookup, out);
  303. }
  304. };
  305. template <>
  306. struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
  307. static v8::Local<v8::Value> ToV8(
  308. v8::Isolate* isolate,
  309. const scoped_refptr<content::DevToolsAgentHost>& val) {
  310. gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
  311. dict.Set("id", val->GetId());
  312. dict.Set("url", val->GetURL().spec());
  313. return dict.GetHandle();
  314. }
  315. };
  316. } // namespace gin
  317. namespace electron::api {
  318. namespace {
  319. constexpr base::StringPiece CursorTypeToString(
  320. ui::mojom::CursorType cursor_type) {
  321. switch (cursor_type) {
  322. case ui::mojom::CursorType::kPointer:
  323. return "pointer";
  324. case ui::mojom::CursorType::kCross:
  325. return "crosshair";
  326. case ui::mojom::CursorType::kHand:
  327. return "hand";
  328. case ui::mojom::CursorType::kIBeam:
  329. return "text";
  330. case ui::mojom::CursorType::kWait:
  331. return "wait";
  332. case ui::mojom::CursorType::kHelp:
  333. return "help";
  334. case ui::mojom::CursorType::kEastResize:
  335. return "e-resize";
  336. case ui::mojom::CursorType::kNorthResize:
  337. return "n-resize";
  338. case ui::mojom::CursorType::kNorthEastResize:
  339. return "ne-resize";
  340. case ui::mojom::CursorType::kNorthWestResize:
  341. return "nw-resize";
  342. case ui::mojom::CursorType::kSouthResize:
  343. return "s-resize";
  344. case ui::mojom::CursorType::kSouthEastResize:
  345. return "se-resize";
  346. case ui::mojom::CursorType::kSouthWestResize:
  347. return "sw-resize";
  348. case ui::mojom::CursorType::kWestResize:
  349. return "w-resize";
  350. case ui::mojom::CursorType::kNorthSouthResize:
  351. return "ns-resize";
  352. case ui::mojom::CursorType::kEastWestResize:
  353. return "ew-resize";
  354. case ui::mojom::CursorType::kNorthEastSouthWestResize:
  355. return "nesw-resize";
  356. case ui::mojom::CursorType::kNorthWestSouthEastResize:
  357. return "nwse-resize";
  358. case ui::mojom::CursorType::kColumnResize:
  359. return "col-resize";
  360. case ui::mojom::CursorType::kRowResize:
  361. return "row-resize";
  362. case ui::mojom::CursorType::kMiddlePanning:
  363. return "m-panning";
  364. case ui::mojom::CursorType::kMiddlePanningVertical:
  365. return "m-panning-vertical";
  366. case ui::mojom::CursorType::kMiddlePanningHorizontal:
  367. return "m-panning-horizontal";
  368. case ui::mojom::CursorType::kEastPanning:
  369. return "e-panning";
  370. case ui::mojom::CursorType::kNorthPanning:
  371. return "n-panning";
  372. case ui::mojom::CursorType::kNorthEastPanning:
  373. return "ne-panning";
  374. case ui::mojom::CursorType::kNorthWestPanning:
  375. return "nw-panning";
  376. case ui::mojom::CursorType::kSouthPanning:
  377. return "s-panning";
  378. case ui::mojom::CursorType::kSouthEastPanning:
  379. return "se-panning";
  380. case ui::mojom::CursorType::kSouthWestPanning:
  381. return "sw-panning";
  382. case ui::mojom::CursorType::kWestPanning:
  383. return "w-panning";
  384. case ui::mojom::CursorType::kMove:
  385. return "move";
  386. case ui::mojom::CursorType::kVerticalText:
  387. return "vertical-text";
  388. case ui::mojom::CursorType::kCell:
  389. return "cell";
  390. case ui::mojom::CursorType::kContextMenu:
  391. return "context-menu";
  392. case ui::mojom::CursorType::kAlias:
  393. return "alias";
  394. case ui::mojom::CursorType::kProgress:
  395. return "progress";
  396. case ui::mojom::CursorType::kNoDrop:
  397. return "nodrop";
  398. case ui::mojom::CursorType::kCopy:
  399. return "copy";
  400. case ui::mojom::CursorType::kNone:
  401. return "none";
  402. case ui::mojom::CursorType::kNotAllowed:
  403. return "not-allowed";
  404. case ui::mojom::CursorType::kZoomIn:
  405. return "zoom-in";
  406. case ui::mojom::CursorType::kZoomOut:
  407. return "zoom-out";
  408. case ui::mojom::CursorType::kGrab:
  409. return "grab";
  410. case ui::mojom::CursorType::kGrabbing:
  411. return "grabbing";
  412. case ui::mojom::CursorType::kCustom:
  413. return "custom";
  414. case ui::mojom::CursorType::kNull:
  415. return "null";
  416. case ui::mojom::CursorType::kDndNone:
  417. return "drag-drop-none";
  418. case ui::mojom::CursorType::kDndMove:
  419. return "drag-drop-move";
  420. case ui::mojom::CursorType::kDndCopy:
  421. return "drag-drop-copy";
  422. case ui::mojom::CursorType::kDndLink:
  423. return "drag-drop-link";
  424. case ui::mojom::CursorType::kNorthSouthNoResize:
  425. return "ns-no-resize";
  426. case ui::mojom::CursorType::kEastWestNoResize:
  427. return "ew-no-resize";
  428. case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
  429. return "nesw-no-resize";
  430. case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
  431. return "nwse-no-resize";
  432. default:
  433. return "default";
  434. }
  435. }
  436. base::IDMap<WebContents*>& GetAllWebContents() {
  437. static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
  438. return *s_all_web_contents;
  439. }
  440. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
  441. base::ScopedClosureRunner capture_handle,
  442. const SkBitmap& bitmap) {
  443. // Hack to enable transparency in captured image
  444. promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
  445. capture_handle.RunAndReset();
  446. }
  447. absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
  448. #if BUILDFLAG(IS_MAC)
  449. absl::optional<base::TimeDelta> system_value(
  450. ui::TextInsertionCaretBlinkPeriodFromDefaults());
  451. if (system_value)
  452. return *system_value;
  453. #elif BUILDFLAG(IS_LINUX)
  454. if (auto* linux_ui = ui::LinuxUi::instance())
  455. return linux_ui->GetCursorBlinkInterval();
  456. #elif BUILDFLAG(IS_WIN)
  457. const auto system_msec = ::GetCaretBlinkTime();
  458. if (system_msec != 0) {
  459. return (system_msec == INFINITE) ? base::TimeDelta()
  460. : base::Milliseconds(system_msec);
  461. }
  462. #endif
  463. return absl::nullopt;
  464. }
  465. #if BUILDFLAG(ENABLE_PRINTING)
  466. // This will return false if no printer with the provided device_name can be
  467. // found on the network. We need to check this because Chromium does not do
  468. // sanity checking of device_name validity and so will crash on invalid names.
  469. bool IsDeviceNameValid(const std::u16string& device_name) {
  470. #if BUILDFLAG(IS_MAC)
  471. base::ScopedCFTypeRef<CFStringRef> new_printer_id(
  472. base::SysUTF16ToCFStringRef(device_name));
  473. PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
  474. bool printer_exists = new_printer != nullptr;
  475. PMRelease(new_printer);
  476. return printer_exists;
  477. #else
  478. scoped_refptr<printing::PrintBackend> print_backend =
  479. printing::PrintBackend::CreateInstance(
  480. g_browser_process->GetApplicationLocale());
  481. return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
  482. #endif
  483. }
  484. // This function returns a validated device name.
  485. // If the user passed one to webContents.print(), we check that it's valid and
  486. // return it or fail if the network doesn't recognize it. If the user didn't
  487. // pass a device name, we first try to return the system default printer. If one
  488. // isn't set, then pull all the printers and use the first one or fail if none
  489. // exist.
  490. std::pair<std::string, std::u16string> GetDeviceNameToUse(
  491. const std::u16string& device_name) {
  492. #if BUILDFLAG(IS_WIN)
  493. // Blocking is needed here because Windows printer drivers are oftentimes
  494. // not thread-safe and have to be accessed on the UI thread.
  495. ScopedAllowBlockingForElectron allow_blocking;
  496. #endif
  497. if (!device_name.empty()) {
  498. if (!IsDeviceNameValid(device_name))
  499. return std::make_pair("Invalid deviceName provided", std::u16string());
  500. return std::make_pair(std::string(), device_name);
  501. }
  502. scoped_refptr<printing::PrintBackend> print_backend =
  503. printing::PrintBackend::CreateInstance(
  504. g_browser_process->GetApplicationLocale());
  505. std::string printer_name;
  506. printing::mojom::ResultCode code =
  507. print_backend->GetDefaultPrinterName(printer_name);
  508. // We don't want to return if this fails since some devices won't have a
  509. // default printer.
  510. if (code != printing::mojom::ResultCode::kSuccess)
  511. LOG(ERROR) << "Failed to get default printer name";
  512. if (printer_name.empty()) {
  513. printing::PrinterList printers;
  514. if (print_backend->EnumeratePrinters(printers) !=
  515. printing::mojom::ResultCode::kSuccess)
  516. return std::make_pair("Failed to enumerate printers", std::u16string());
  517. if (printers.empty())
  518. return std::make_pair("No printers available on the network",
  519. std::u16string());
  520. printer_name = printers.front().printer_name;
  521. }
  522. return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
  523. }
  524. // Copied from
  525. // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
  526. scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
  527. // USER_VISIBLE because the result is displayed in the print preview dialog.
  528. #if !BUILDFLAG(IS_WIN)
  529. static constexpr base::TaskTraits kTraits = {
  530. base::MayBlock(), base::TaskPriority::USER_VISIBLE};
  531. #endif
  532. #if defined(USE_CUPS)
  533. // CUPS is thread safe.
  534. return base::ThreadPool::CreateTaskRunner(kTraits);
  535. #elif BUILDFLAG(IS_WIN)
  536. // Windows drivers are likely not thread-safe and need to be accessed on the
  537. // UI thread.
  538. return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
  539. #else
  540. // Be conservative on unsupported platforms.
  541. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
  542. #endif
  543. }
  544. #endif
  545. struct UserDataLink : public base::SupportsUserData::Data {
  546. explicit UserDataLink(base::WeakPtr<WebContents> contents)
  547. : web_contents(contents) {}
  548. base::WeakPtr<WebContents> web_contents;
  549. };
  550. const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
  551. const char kRootName[] = "<root>";
  552. struct FileSystem {
  553. FileSystem() = default;
  554. FileSystem(const std::string& type,
  555. const std::string& file_system_name,
  556. const std::string& root_url,
  557. const std::string& file_system_path)
  558. : type(type),
  559. file_system_name(file_system_name),
  560. root_url(root_url),
  561. file_system_path(file_system_path) {}
  562. std::string type;
  563. std::string file_system_name;
  564. std::string root_url;
  565. std::string file_system_path;
  566. };
  567. std::string RegisterFileSystem(content::WebContents* web_contents,
  568. const base::FilePath& path) {
  569. auto* isolated_context = storage::IsolatedContext::GetInstance();
  570. std::string root_name(kRootName);
  571. storage::IsolatedContext::ScopedFSHandle file_system =
  572. isolated_context->RegisterFileSystemForPath(
  573. storage::kFileSystemTypeLocal, std::string(), path, &root_name);
  574. content::ChildProcessSecurityPolicy* policy =
  575. content::ChildProcessSecurityPolicy::GetInstance();
  576. content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
  577. int renderer_id = render_view_host->GetProcess()->GetID();
  578. policy->GrantReadFileSystem(renderer_id, file_system.id());
  579. policy->GrantWriteFileSystem(renderer_id, file_system.id());
  580. policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
  581. policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
  582. if (!policy->CanReadFile(renderer_id, path))
  583. policy->GrantReadFile(renderer_id, path);
  584. return file_system.id();
  585. }
  586. FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
  587. const std::string& file_system_id,
  588. const std::string& file_system_path,
  589. const std::string& type) {
  590. const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
  591. std::string file_system_name =
  592. storage::GetIsolatedFileSystemName(origin, file_system_id);
  593. std::string root_url = storage::GetIsolatedFileSystemRootURIString(
  594. origin, file_system_id, kRootName);
  595. return FileSystem(type, file_system_name, root_url, file_system_path);
  596. }
  597. base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
  598. base::Value::Dict value;
  599. value.Set("type", file_system.type);
  600. value.Set("fileSystemName", file_system.file_system_name);
  601. value.Set("rootURL", file_system.root_url);
  602. value.Set("fileSystemPath", file_system.file_system_path);
  603. return value;
  604. }
  605. void WriteToFile(const base::FilePath& path, const std::string& content) {
  606. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  607. base::BlockingType::WILL_BLOCK);
  608. DCHECK(!path.empty());
  609. base::WriteFile(path, content.data(), content.size());
  610. }
  611. void AppendToFile(const base::FilePath& path, const std::string& content) {
  612. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  613. base::BlockingType::WILL_BLOCK);
  614. DCHECK(!path.empty());
  615. base::AppendToFile(path, content);
  616. }
  617. PrefService* GetPrefService(content::WebContents* web_contents) {
  618. auto* context = web_contents->GetBrowserContext();
  619. return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
  620. }
  621. std::map<std::string, std::string> GetAddedFileSystemPaths(
  622. content::WebContents* web_contents) {
  623. auto* pref_service = GetPrefService(web_contents);
  624. const base::Value::Dict& file_system_paths =
  625. pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
  626. std::map<std::string, std::string> result;
  627. for (auto it : file_system_paths) {
  628. std::string type =
  629. it.second.is_string() ? it.second.GetString() : std::string();
  630. result[it.first] = type;
  631. }
  632. return result;
  633. }
  634. bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
  635. const std::string& file_system_path) {
  636. return base::Contains(GetAddedFileSystemPaths(web_contents),
  637. file_system_path);
  638. }
  639. void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
  640. rwhv->SetBackgroundColor(color);
  641. static_cast<content::RenderWidgetHostViewBase*>(rwhv)
  642. ->SetContentBackgroundColor(color);
  643. }
  644. content::RenderFrameHost* GetRenderFrameHost(
  645. content::NavigationHandle* navigation_handle) {
  646. int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
  647. content::FrameTreeNode* frame_tree_node =
  648. content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
  649. content::RenderFrameHostManager* render_manager =
  650. frame_tree_node->render_manager();
  651. content::RenderFrameHost* frame_host = nullptr;
  652. if (render_manager) {
  653. frame_host = render_manager->speculative_frame_host();
  654. if (!frame_host)
  655. frame_host = render_manager->current_frame_host();
  656. }
  657. return frame_host;
  658. }
  659. } // namespace
  660. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  661. WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
  662. switch (view_type) {
  663. case extensions::mojom::ViewType::kExtensionBackgroundPage:
  664. return WebContents::Type::kBackgroundPage;
  665. case extensions::mojom::ViewType::kAppWindow:
  666. case extensions::mojom::ViewType::kComponent:
  667. case extensions::mojom::ViewType::kExtensionDialog:
  668. case extensions::mojom::ViewType::kExtensionPopup:
  669. case extensions::mojom::ViewType::kBackgroundContents:
  670. case extensions::mojom::ViewType::kExtensionGuest:
  671. case extensions::mojom::ViewType::kTabContents:
  672. case extensions::mojom::ViewType::kOffscreenDocument:
  673. case extensions::mojom::ViewType::kExtensionSidePanel:
  674. case extensions::mojom::ViewType::kInvalid:
  675. return WebContents::Type::kRemote;
  676. }
  677. }
  678. #endif
  679. WebContents::WebContents(v8::Isolate* isolate,
  680. content::WebContents* web_contents)
  681. : content::WebContentsObserver(web_contents),
  682. type_(Type::kRemote),
  683. id_(GetAllWebContents().Add(this))
  684. #if BUILDFLAG(ENABLE_PRINTING)
  685. ,
  686. print_task_runner_(CreatePrinterHandlerTaskRunner())
  687. #endif
  688. {
  689. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  690. // WebContents created by extension host will have valid ViewType set.
  691. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
  692. if (view_type != extensions::mojom::ViewType::kInvalid) {
  693. InitWithExtensionView(isolate, web_contents, view_type);
  694. }
  695. extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
  696. web_contents);
  697. script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
  698. #endif
  699. auto session = Session::CreateFrom(isolate, GetBrowserContext());
  700. session_.Reset(isolate, session.ToV8());
  701. SetUserAgent(GetBrowserContext()->GetUserAgent());
  702. web_contents->SetUserData(kElectronApiWebContentsKey,
  703. std::make_unique<UserDataLink>(GetWeakPtr()));
  704. InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
  705. }
  706. WebContents::WebContents(v8::Isolate* isolate,
  707. std::unique_ptr<content::WebContents> web_contents,
  708. Type type)
  709. : content::WebContentsObserver(web_contents.get()),
  710. type_(type),
  711. id_(GetAllWebContents().Add(this))
  712. #if BUILDFLAG(ENABLE_PRINTING)
  713. ,
  714. print_task_runner_(CreatePrinterHandlerTaskRunner())
  715. #endif
  716. {
  717. DCHECK(type != Type::kRemote)
  718. << "Can't take ownership of a remote WebContents";
  719. auto session = Session::CreateFrom(isolate, GetBrowserContext());
  720. session_.Reset(isolate, session.ToV8());
  721. InitWithSessionAndOptions(isolate, std::move(web_contents), session,
  722. gin::Dictionary::CreateEmpty(isolate));
  723. }
  724. WebContents::WebContents(v8::Isolate* isolate,
  725. const gin_helper::Dictionary& options)
  726. : id_(GetAllWebContents().Add(this))
  727. #if BUILDFLAG(ENABLE_PRINTING)
  728. ,
  729. print_task_runner_(CreatePrinterHandlerTaskRunner())
  730. #endif
  731. {
  732. // Read options.
  733. options.Get("backgroundThrottling", &background_throttling_);
  734. // Get type
  735. options.Get("type", &type_);
  736. bool b = false;
  737. if (options.Get(options::kOffscreen, &b) && b)
  738. type_ = Type::kOffScreen;
  739. // Init embedder earlier
  740. options.Get("embedder", &embedder_);
  741. // Whether to enable DevTools.
  742. options.Get("devTools", &enable_devtools_);
  743. // BrowserViews are not attached to a window initially so they should start
  744. // off as hidden. This is also important for compositor recycling. See:
  745. // https://github.com/electron/electron/pull/21372
  746. bool initially_shown = type_ != Type::kBrowserView;
  747. options.Get(options::kShow, &initially_shown);
  748. // Obtain the session.
  749. std::string partition;
  750. gin::Handle<api::Session> session;
  751. if (options.Get("session", &session) && !session.IsEmpty()) {
  752. } else if (options.Get("partition", &partition)) {
  753. session = Session::FromPartition(isolate, partition);
  754. } else {
  755. // Use the default session if not specified.
  756. session = Session::FromPartition(isolate, "");
  757. }
  758. session_.Reset(isolate, session.ToV8());
  759. std::unique_ptr<content::WebContents> web_contents;
  760. if (IsGuest()) {
  761. scoped_refptr<content::SiteInstance> site_instance =
  762. content::SiteInstance::CreateForURL(session->browser_context(),
  763. GURL("chrome-guest://fake-host"));
  764. content::WebContents::CreateParams params(session->browser_context(),
  765. site_instance);
  766. guest_delegate_ =
  767. std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
  768. params.guest_delegate = guest_delegate_.get();
  769. if (embedder_ && embedder_->IsOffScreen()) {
  770. auto* view = new OffScreenWebContentsView(
  771. false,
  772. base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
  773. params.view = view;
  774. params.delegate_view = view;
  775. web_contents = content::WebContents::Create(params);
  776. view->SetWebContents(web_contents.get());
  777. } else {
  778. web_contents = content::WebContents::Create(params);
  779. }
  780. } else if (IsOffScreen()) {
  781. // webPreferences does not have a transparent option, so if the window needs
  782. // to be transparent, that will be set at electron_api_browser_window.cc#L57
  783. // and we then need to pull it back out and check it here.
  784. std::string background_color;
  785. options.GetHidden(options::kBackgroundColor, &background_color);
  786. bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
  787. content::WebContents::CreateParams params(session->browser_context());
  788. auto* view = new OffScreenWebContentsView(
  789. transparent,
  790. base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
  791. params.view = view;
  792. params.delegate_view = view;
  793. web_contents = content::WebContents::Create(params);
  794. view->SetWebContents(web_contents.get());
  795. } else {
  796. content::WebContents::CreateParams params(session->browser_context());
  797. params.initially_hidden = !initially_shown;
  798. web_contents = content::WebContents::Create(params);
  799. }
  800. InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
  801. }
  802. void WebContents::InitZoomController(content::WebContents* web_contents,
  803. const gin_helper::Dictionary& options) {
  804. WebContentsZoomController::CreateForWebContents(web_contents);
  805. zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
  806. double zoom_factor;
  807. if (options.Get(options::kZoomFactor, &zoom_factor))
  808. zoom_controller_->SetDefaultZoomFactor(zoom_factor);
  809. // Nothing to do with ZoomController, but this function gets called in all
  810. // init cases!
  811. content::RenderViewHost* host = web_contents->GetRenderViewHost();
  812. if (host)
  813. host->GetWidget()->AddInputEventObserver(this);
  814. }
  815. void WebContents::InitWithSessionAndOptions(
  816. v8::Isolate* isolate,
  817. std::unique_ptr<content::WebContents> owned_web_contents,
  818. gin::Handle<api::Session> session,
  819. const gin_helper::Dictionary& options) {
  820. Observe(owned_web_contents.get());
  821. InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
  822. IsGuest());
  823. inspectable_web_contents_->GetView()->SetDelegate(this);
  824. auto* prefs = web_contents()->GetMutableRendererPrefs();
  825. // Collect preferred languages from OS and browser process. accept_languages
  826. // effects HTTP header, navigator.languages, and CJK fallback font selection.
  827. //
  828. // Note that an application locale set to the browser process might be
  829. // different with the one set to the preference list.
  830. // (e.g. overridden with --lang)
  831. std::string accept_languages =
  832. g_browser_process->GetApplicationLocale() + ",";
  833. for (auto const& language : electron::GetPreferredLanguages()) {
  834. if (language == g_browser_process->GetApplicationLocale())
  835. continue;
  836. accept_languages += language + ",";
  837. }
  838. accept_languages.pop_back();
  839. prefs->accept_languages = accept_languages;
  840. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
  841. // Update font settings.
  842. static const gfx::FontRenderParams params(
  843. gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
  844. prefs->should_antialias_text = params.antialiasing;
  845. prefs->use_subpixel_positioning = params.subpixel_positioning;
  846. prefs->hinting = params.hinting;
  847. prefs->use_autohinter = params.autohinter;
  848. prefs->use_bitmaps = params.use_bitmaps;
  849. prefs->subpixel_rendering = params.subpixel_rendering;
  850. #endif
  851. // Honor the system's cursor blink rate settings
  852. if (auto interval = GetCursorBlinkInterval())
  853. prefs->caret_blink_interval = *interval;
  854. // Save the preferences in C++.
  855. // If there's already a WebContentsPreferences object, we created it as part
  856. // of the webContents.setWindowOpenHandler path, so don't overwrite it.
  857. if (!WebContentsPreferences::From(web_contents())) {
  858. new WebContentsPreferences(web_contents(), options);
  859. }
  860. // Trigger re-calculation of webkit prefs.
  861. web_contents()->NotifyPreferencesChanged();
  862. WebContentsPermissionHelper::CreateForWebContents(web_contents());
  863. InitZoomController(web_contents(), options);
  864. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  865. extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
  866. web_contents());
  867. script_executor_ =
  868. std::make_unique<extensions::ScriptExecutor>(web_contents());
  869. #endif
  870. AutofillDriverFactory::CreateForWebContents(web_contents());
  871. SetUserAgent(GetBrowserContext()->GetUserAgent());
  872. if (IsGuest()) {
  873. NativeWindow* owner_window = nullptr;
  874. if (embedder_) {
  875. // New WebContents's owner_window is the embedder's owner_window.
  876. auto* relay =
  877. NativeWindowRelay::FromWebContents(embedder_->web_contents());
  878. if (relay)
  879. owner_window = relay->GetNativeWindow();
  880. }
  881. if (owner_window)
  882. SetOwnerWindow(owner_window);
  883. }
  884. web_contents()->SetUserData(kElectronApiWebContentsKey,
  885. std::make_unique<UserDataLink>(GetWeakPtr()));
  886. }
  887. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  888. void WebContents::InitWithExtensionView(v8::Isolate* isolate,
  889. content::WebContents* web_contents,
  890. extensions::mojom::ViewType view_type) {
  891. // Must reassign type prior to calling `Init`.
  892. type_ = GetTypeFromViewType(view_type);
  893. if (type_ == Type::kRemote)
  894. return;
  895. if (type_ == Type::kBackgroundPage)
  896. // non-background-page WebContents are retained by other classes. We need
  897. // to pin here to prevent background-page WebContents from being GC'd.
  898. // The background page api::WebContents will live until the underlying
  899. // content::WebContents is destroyed.
  900. Pin(isolate);
  901. // Allow toggling DevTools for background pages
  902. Observe(web_contents);
  903. InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
  904. GetBrowserContext(), IsGuest());
  905. inspectable_web_contents_->GetView()->SetDelegate(this);
  906. }
  907. #endif
  908. void WebContents::InitWithWebContents(
  909. std::unique_ptr<content::WebContents> web_contents,
  910. ElectronBrowserContext* browser_context,
  911. bool is_guest) {
  912. browser_context_ = browser_context;
  913. web_contents->SetDelegate(this);
  914. #if BUILDFLAG(ENABLE_PRINTING)
  915. PrintViewManagerElectron::CreateForWebContents(web_contents.get());
  916. #endif
  917. #if BUILDFLAG(ENABLE_PDF_VIEWER)
  918. pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
  919. web_contents.get(),
  920. std::make_unique<ElectronPDFWebContentsHelperClient>());
  921. #endif
  922. // Determine whether the WebContents is offscreen.
  923. auto* web_preferences = WebContentsPreferences::From(web_contents.get());
  924. offscreen_ = web_preferences && web_preferences->IsOffscreen();
  925. // Create InspectableWebContents.
  926. inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
  927. std::move(web_contents), browser_context->prefs(), is_guest);
  928. inspectable_web_contents_->SetDelegate(this);
  929. }
  930. WebContents::~WebContents() {
  931. if (web_contents()) {
  932. content::RenderViewHost* host = web_contents()->GetRenderViewHost();
  933. if (host)
  934. host->GetWidget()->RemoveInputEventObserver(this);
  935. }
  936. if (!inspectable_web_contents_) {
  937. WebContentsDestroyed();
  938. return;
  939. }
  940. inspectable_web_contents_->GetView()->SetDelegate(nullptr);
  941. // This event is only for internal use, which is emitted when WebContents is
  942. // being destroyed.
  943. Emit("will-destroy");
  944. // For guest view based on OOPIF, the WebContents is released by the embedder
  945. // frame, and we need to clear the reference to the memory.
  946. bool not_owned_by_this = IsGuest() && attached_;
  947. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  948. // And background pages are owned by extensions::ExtensionHost.
  949. if (type_ == Type::kBackgroundPage)
  950. not_owned_by_this = true;
  951. #endif
  952. if (not_owned_by_this) {
  953. inspectable_web_contents_->ReleaseWebContents();
  954. WebContentsDestroyed();
  955. }
  956. // InspectableWebContents will be automatically destroyed.
  957. }
  958. void WebContents::DeleteThisIfAlive() {
  959. // It is possible that the FirstWeakCallback has been called but the
  960. // SecondWeakCallback has not, in this case the garbage collection of
  961. // WebContents has already started and we should not |delete this|.
  962. // Calling |GetWrapper| can detect this corner case.
  963. auto* isolate = JavascriptEnvironment::GetIsolate();
  964. v8::HandleScope scope(isolate);
  965. v8::Local<v8::Object> wrapper;
  966. if (!GetWrapper(isolate).ToLocal(&wrapper))
  967. return;
  968. delete this;
  969. }
  970. void WebContents::Destroy() {
  971. // The content::WebContents should be destroyed asynchronously when possible
  972. // as user may choose to destroy WebContents during an event of it.
  973. if (Browser::Get()->is_shutting_down() || IsGuest()) {
  974. DeleteThisIfAlive();
  975. } else {
  976. content::GetUIThreadTaskRunner({})->PostTask(
  977. FROM_HERE,
  978. base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
  979. }
  980. }
  981. void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
  982. bool dispatch_beforeunload = false;
  983. if (options)
  984. options->Get("waitForBeforeUnload", &dispatch_beforeunload);
  985. if (dispatch_beforeunload &&
  986. web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
  987. NotifyUserActivation();
  988. web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
  989. } else {
  990. web_contents()->Close();
  991. }
  992. }
  993. bool WebContents::DidAddMessageToConsole(
  994. content::WebContents* source,
  995. blink::mojom::ConsoleMessageLevel level,
  996. const std::u16string& message,
  997. int32_t line_no,
  998. const std::u16string& source_id) {
  999. return Emit("console-message", static_cast<int32_t>(level), message, line_no,
  1000. source_id);
  1001. }
  1002. void WebContents::OnCreateWindow(
  1003. const GURL& target_url,
  1004. const content::Referrer& referrer,
  1005. const std::string& frame_name,
  1006. WindowOpenDisposition disposition,
  1007. const std::string& features,
  1008. const scoped_refptr<network::ResourceRequestBody>& body) {
  1009. Emit("-new-window", target_url, frame_name, disposition, features, referrer,
  1010. body);
  1011. }
  1012. void WebContents::WebContentsCreatedWithFullParams(
  1013. content::WebContents* source_contents,
  1014. int opener_render_process_id,
  1015. int opener_render_frame_id,
  1016. const content::mojom::CreateNewWindowParams& params,
  1017. content::WebContents* new_contents) {
  1018. ChildWebContentsTracker::CreateForWebContents(new_contents);
  1019. auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
  1020. tracker->url = params.target_url;
  1021. tracker->frame_name = params.frame_name;
  1022. tracker->referrer = params.referrer.To<content::Referrer>();
  1023. tracker->raw_features = params.raw_features;
  1024. tracker->body = params.body;
  1025. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1026. v8::HandleScope handle_scope(isolate);
  1027. gin_helper::Dictionary dict;
  1028. gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
  1029. &dict);
  1030. pending_child_web_preferences_.Reset();
  1031. // Associate the preferences passed in via `setWindowOpenHandler` with the
  1032. // content::WebContents that was just created for the child window. These
  1033. // preferences will be picked up by the RenderWidgetHost via its call to the
  1034. // delegate's OverrideWebkitPrefs.
  1035. new WebContentsPreferences(new_contents, dict);
  1036. }
  1037. bool WebContents::IsWebContentsCreationOverridden(
  1038. content::SiteInstance* source_site_instance,
  1039. content::mojom::WindowContainerType window_container_type,
  1040. const GURL& opener_url,
  1041. const content::mojom::CreateNewWindowParams& params) {
  1042. bool default_prevented = Emit(
  1043. "-will-add-new-contents", params.target_url, params.frame_name,
  1044. params.raw_features, params.disposition, *params.referrer, params.body);
  1045. // If the app prevented the default, redirect to CreateCustomWebContents,
  1046. // which always returns nullptr, which will result in the window open being
  1047. // prevented (window.open() will return null in the renderer).
  1048. return default_prevented;
  1049. }
  1050. void WebContents::SetNextChildWebPreferences(
  1051. const gin_helper::Dictionary preferences) {
  1052. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1053. v8::HandleScope handle_scope(isolate);
  1054. // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
  1055. // with the new child contents.
  1056. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
  1057. }
  1058. content::WebContents* WebContents::CreateCustomWebContents(
  1059. content::RenderFrameHost* opener,
  1060. content::SiteInstance* source_site_instance,
  1061. bool is_new_browsing_instance,
  1062. const GURL& opener_url,
  1063. const std::string& frame_name,
  1064. const GURL& target_url,
  1065. const content::StoragePartitionConfig& partition_config,
  1066. content::SessionStorageNamespace* session_storage_namespace) {
  1067. return nullptr;
  1068. }
  1069. void WebContents::AddNewContents(
  1070. content::WebContents* source,
  1071. std::unique_ptr<content::WebContents> new_contents,
  1072. const GURL& target_url,
  1073. WindowOpenDisposition disposition,
  1074. const blink::mojom::WindowFeatures& window_features,
  1075. bool user_gesture,
  1076. bool* was_blocked) {
  1077. auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
  1078. DCHECK(tracker);
  1079. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1080. v8::HandleScope handle_scope(isolate);
  1081. auto api_web_contents =
  1082. CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
  1083. // We call RenderFrameCreated here as at this point the empty "about:blank"
  1084. // render frame has already been created. If the window never navigates again
  1085. // RenderFrameCreated won't be called and certain prefs like
  1086. // "kBackgroundColor" will not be applied.
  1087. auto* frame = api_web_contents->MainFrame();
  1088. if (frame) {
  1089. api_web_contents->HandleNewRenderFrame(frame);
  1090. }
  1091. if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
  1092. window_features.bounds.x(), window_features.bounds.y(),
  1093. window_features.bounds.width(), window_features.bounds.height(),
  1094. tracker->url, tracker->frame_name, tracker->referrer,
  1095. tracker->raw_features, tracker->body)) {
  1096. api_web_contents->Destroy();
  1097. }
  1098. }
  1099. content::WebContents* WebContents::OpenURLFromTab(
  1100. content::WebContents* source,
  1101. const content::OpenURLParams& params) {
  1102. auto weak_this = GetWeakPtr();
  1103. if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
  1104. Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
  1105. params.post_data);
  1106. return nullptr;
  1107. }
  1108. if (!weak_this || !web_contents())
  1109. return nullptr;
  1110. content::NavigationController::LoadURLParams load_url_params(params.url);
  1111. load_url_params.referrer = params.referrer;
  1112. load_url_params.transition_type = params.transition;
  1113. load_url_params.extra_headers = params.extra_headers;
  1114. load_url_params.should_replace_current_entry =
  1115. params.should_replace_current_entry;
  1116. load_url_params.is_renderer_initiated = params.is_renderer_initiated;
  1117. load_url_params.started_from_context_menu = params.started_from_context_menu;
  1118. load_url_params.initiator_origin = params.initiator_origin;
  1119. load_url_params.source_site_instance = params.source_site_instance;
  1120. load_url_params.frame_tree_node_id = params.frame_tree_node_id;
  1121. load_url_params.redirect_chain = params.redirect_chain;
  1122. load_url_params.has_user_gesture = params.user_gesture;
  1123. load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
  1124. load_url_params.href_translate = params.href_translate;
  1125. load_url_params.reload_type = params.reload_type;
  1126. if (params.post_data) {
  1127. load_url_params.load_type =
  1128. content::NavigationController::LOAD_TYPE_HTTP_POST;
  1129. load_url_params.post_data = params.post_data;
  1130. }
  1131. source->GetController().LoadURLWithParams(load_url_params);
  1132. return source;
  1133. }
  1134. void WebContents::BeforeUnloadFired(content::WebContents* tab,
  1135. bool proceed,
  1136. bool* proceed_to_fire_unload) {
  1137. if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
  1138. type_ == Type::kBrowserView)
  1139. *proceed_to_fire_unload = proceed;
  1140. else
  1141. *proceed_to_fire_unload = true;
  1142. // Note that Chromium does not emit this for navigations.
  1143. Emit("before-unload-fired", proceed);
  1144. }
  1145. void WebContents::SetContentsBounds(content::WebContents* source,
  1146. const gfx::Rect& rect) {
  1147. if (!Emit("content-bounds-updated", rect))
  1148. for (ExtendedWebContentsObserver& observer : observers_)
  1149. observer.OnSetContentBounds(rect);
  1150. }
  1151. void WebContents::CloseContents(content::WebContents* source) {
  1152. Emit("close");
  1153. auto* autofill_driver_factory =
  1154. AutofillDriverFactory::FromWebContents(web_contents());
  1155. if (autofill_driver_factory) {
  1156. autofill_driver_factory->CloseAllPopups();
  1157. }
  1158. for (ExtendedWebContentsObserver& observer : observers_)
  1159. observer.OnCloseContents();
  1160. // This is handled by the embedder frame.
  1161. if (!IsGuest())
  1162. Destroy();
  1163. }
  1164. void WebContents::ActivateContents(content::WebContents* source) {
  1165. for (ExtendedWebContentsObserver& observer : observers_)
  1166. observer.OnActivateContents();
  1167. }
  1168. void WebContents::UpdateTargetURL(content::WebContents* source,
  1169. const GURL& url) {
  1170. Emit("update-target-url", url);
  1171. }
  1172. bool WebContents::HandleKeyboardEvent(
  1173. content::WebContents* source,
  1174. const content::NativeWebKeyboardEvent& event) {
  1175. if (type_ == Type::kWebView && embedder_) {
  1176. // Send the unhandled keyboard events back to the embedder.
  1177. return embedder_->HandleKeyboardEvent(source, event);
  1178. } else {
  1179. return PlatformHandleKeyboardEvent(source, event);
  1180. }
  1181. }
  1182. #if !BUILDFLAG(IS_MAC)
  1183. // NOTE: The macOS version of this function is found in
  1184. // electron_api_web_contents_mac.mm, as it requires calling into objective-C
  1185. // code.
  1186. bool WebContents::PlatformHandleKeyboardEvent(
  1187. content::WebContents* source,
  1188. const content::NativeWebKeyboardEvent& event) {
  1189. // Escape exits tabbed fullscreen mode.
  1190. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
  1191. ExitFullscreenModeForTab(source);
  1192. return true;
  1193. }
  1194. // Check if the webContents has preferences and to ignore shortcuts
  1195. auto* web_preferences = WebContentsPreferences::From(source);
  1196. if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
  1197. return false;
  1198. // Let the NativeWindow handle other parts.
  1199. if (owner_window()) {
  1200. owner_window()->HandleKeyboardEvent(source, event);
  1201. return true;
  1202. }
  1203. return false;
  1204. }
  1205. #endif
  1206. content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
  1207. content::WebContents* source,
  1208. const content::NativeWebKeyboardEvent& event) {
  1209. if (exclusive_access_manager_.HandleUserKeyEvent(event))
  1210. return content::KeyboardEventProcessingResult::HANDLED;
  1211. if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
  1212. event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
  1213. // For backwards compatibility, pretend that `kRawKeyDown` events are
  1214. // actually `kKeyDown`.
  1215. content::NativeWebKeyboardEvent tweaked_event(event);
  1216. if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
  1217. tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
  1218. bool prevent_default = Emit("before-input-event", tweaked_event);
  1219. if (prevent_default) {
  1220. return content::KeyboardEventProcessingResult::HANDLED;
  1221. }
  1222. }
  1223. return content::KeyboardEventProcessingResult::NOT_HANDLED;
  1224. }
  1225. void WebContents::ContentsZoomChange(bool zoom_in) {
  1226. Emit("zoom-changed", zoom_in ? "in" : "out");
  1227. }
  1228. Profile* WebContents::GetProfile() {
  1229. return nullptr;
  1230. }
  1231. bool WebContents::IsFullscreen() const {
  1232. if (!owner_window())
  1233. return false;
  1234. return owner_window()->IsFullscreen() || is_html_fullscreen();
  1235. }
  1236. void WebContents::EnterFullscreen(const GURL& url,
  1237. ExclusiveAccessBubbleType bubble_type,
  1238. const int64_t display_id) {}
  1239. void WebContents::ExitFullscreen() {}
  1240. void WebContents::UpdateExclusiveAccessExitBubbleContent(
  1241. const GURL& url,
  1242. ExclusiveAccessBubbleType bubble_type,
  1243. ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
  1244. bool notify_download,
  1245. bool force_update) {}
  1246. void WebContents::OnExclusiveAccessUserInput() {}
  1247. content::WebContents* WebContents::GetActiveWebContents() {
  1248. return web_contents();
  1249. }
  1250. bool WebContents::CanUserExitFullscreen() const {
  1251. return true;
  1252. }
  1253. bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
  1254. return false;
  1255. }
  1256. void WebContents::EnterFullscreenModeForTab(
  1257. content::RenderFrameHost* requesting_frame,
  1258. const blink::mojom::FullscreenOptions& options) {
  1259. auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
  1260. auto* permission_helper =
  1261. WebContentsPermissionHelper::FromWebContents(source);
  1262. auto callback =
  1263. base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
  1264. base::Unretained(this), requesting_frame, options);
  1265. permission_helper->RequestFullscreenPermission(requesting_frame, callback);
  1266. }
  1267. void WebContents::OnEnterFullscreenModeForTab(
  1268. content::RenderFrameHost* requesting_frame,
  1269. const blink::mojom::FullscreenOptions& options,
  1270. bool allowed) {
  1271. if (!allowed || !owner_window())
  1272. return;
  1273. auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
  1274. if (IsFullscreenForTabOrPending(source)) {
  1275. DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
  1276. return;
  1277. }
  1278. owner_window()->set_fullscreen_transition_type(
  1279. NativeWindow::FullScreenTransitionType::kHTML);
  1280. exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
  1281. requesting_frame, options.display_id);
  1282. SetHtmlApiFullscreen(true);
  1283. if (native_fullscreen_) {
  1284. // Explicitly trigger a view resize, as the size is not actually changing if
  1285. // the browser is fullscreened, too.
  1286. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
  1287. }
  1288. }
  1289. void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
  1290. if (!owner_window())
  1291. return;
  1292. // This needs to be called before we exit fullscreen on the native window,
  1293. // or the controller will incorrectly think we weren't fullscreen and bail.
  1294. exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
  1295. source);
  1296. SetHtmlApiFullscreen(false);
  1297. if (native_fullscreen_) {
  1298. // Explicitly trigger a view resize, as the size is not actually changing if
  1299. // the browser is fullscreened, too. Chrome does this indirectly from
  1300. // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
  1301. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
  1302. }
  1303. }
  1304. void WebContents::RendererUnresponsive(
  1305. content::WebContents* source,
  1306. content::RenderWidgetHost* render_widget_host,
  1307. base::RepeatingClosure hang_monitor_restarter) {
  1308. Emit("unresponsive");
  1309. }
  1310. void WebContents::RendererResponsive(
  1311. content::WebContents* source,
  1312. content::RenderWidgetHost* render_widget_host) {
  1313. Emit("responsive");
  1314. }
  1315. bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
  1316. const content::ContextMenuParams& params) {
  1317. Emit("context-menu", std::make_pair(params, &render_frame_host));
  1318. return true;
  1319. }
  1320. void WebContents::FindReply(content::WebContents* web_contents,
  1321. int request_id,
  1322. int number_of_matches,
  1323. const gfx::Rect& selection_rect,
  1324. int active_match_ordinal,
  1325. bool final_update) {
  1326. if (!final_update)
  1327. return;
  1328. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1329. v8::HandleScope handle_scope(isolate);
  1330. gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate);
  1331. result.Set("requestId", request_id);
  1332. result.Set("matches", number_of_matches);
  1333. result.Set("selectionArea", selection_rect);
  1334. result.Set("activeMatchOrdinal", active_match_ordinal);
  1335. result.Set("finalUpdate", final_update); // Deprecate after 2.0
  1336. Emit("found-in-page", result.GetHandle());
  1337. }
  1338. void WebContents::RequestExclusivePointerAccess(
  1339. content::WebContents* web_contents,
  1340. bool user_gesture,
  1341. bool last_unlocked_by_target,
  1342. bool allowed) {
  1343. if (allowed) {
  1344. exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse(
  1345. web_contents, user_gesture, last_unlocked_by_target);
  1346. } else {
  1347. web_contents->GotResponseToLockMouseRequest(
  1348. blink::mojom::PointerLockResult::kPermissionDenied);
  1349. }
  1350. }
  1351. void WebContents::RequestToLockMouse(content::WebContents* web_contents,
  1352. bool user_gesture,
  1353. bool last_unlocked_by_target) {
  1354. auto* permission_helper =
  1355. WebContentsPermissionHelper::FromWebContents(web_contents);
  1356. permission_helper->RequestPointerLockPermission(
  1357. user_gesture, last_unlocked_by_target,
  1358. base::BindOnce(&WebContents::RequestExclusivePointerAccess,
  1359. base::Unretained(this)));
  1360. }
  1361. void WebContents::LostMouseLock() {
  1362. exclusive_access_manager_.mouse_lock_controller()->LostMouseLock();
  1363. }
  1364. void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
  1365. bool esc_key_locked) {
  1366. exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock(
  1367. web_contents, esc_key_locked);
  1368. }
  1369. void WebContents::CancelKeyboardLockRequest(
  1370. content::WebContents* web_contents) {
  1371. exclusive_access_manager_.keyboard_lock_controller()
  1372. ->CancelKeyboardLockRequest(web_contents);
  1373. }
  1374. bool WebContents::CheckMediaAccessPermission(
  1375. content::RenderFrameHost* render_frame_host,
  1376. const GURL& security_origin,
  1377. blink::mojom::MediaStreamType type) {
  1378. auto* web_contents =
  1379. content::WebContents::FromRenderFrameHost(render_frame_host);
  1380. auto* permission_helper =
  1381. WebContentsPermissionHelper::FromWebContents(web_contents);
  1382. return permission_helper->CheckMediaAccessPermission(security_origin, type);
  1383. }
  1384. void WebContents::RequestMediaAccessPermission(
  1385. content::WebContents* web_contents,
  1386. const content::MediaStreamRequest& request,
  1387. content::MediaResponseCallback callback) {
  1388. auto* permission_helper =
  1389. WebContentsPermissionHelper::FromWebContents(web_contents);
  1390. permission_helper->RequestMediaAccessPermission(request, std::move(callback));
  1391. }
  1392. content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
  1393. content::WebContents* source) {
  1394. if (!dialog_manager_)
  1395. dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
  1396. return dialog_manager_.get();
  1397. }
  1398. void WebContents::OnAudioStateChanged(bool audible) {
  1399. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1400. v8::HandleScope handle_scope(isolate);
  1401. gin::Handle<gin_helper::internal::Event> event =
  1402. gin_helper::internal::Event::New(isolate);
  1403. v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
  1404. gin::Dictionary dict(isolate, event_object);
  1405. dict.Set("audible", audible);
  1406. EmitWithoutEvent("audio-state-changed", event);
  1407. }
  1408. void WebContents::BeforeUnloadFired(bool proceed) {
  1409. // Do nothing, we override this method just to avoid compilation error since
  1410. // there are two virtual functions named BeforeUnloadFired.
  1411. }
  1412. void WebContents::HandleNewRenderFrame(
  1413. content::RenderFrameHost* render_frame_host) {
  1414. auto* rwhv = render_frame_host->GetView();
  1415. if (!rwhv)
  1416. return;
  1417. // Set the background color of RenderWidgetHostView.
  1418. auto* web_preferences = WebContentsPreferences::From(web_contents());
  1419. if (web_preferences) {
  1420. auto maybe_color = web_preferences->GetBackgroundColor();
  1421. bool guest = IsGuest() || type_ == Type::kBrowserView;
  1422. // If webPreferences has no color stored we need to explicitly set guest
  1423. // webContents background color to transparent.
  1424. auto bg_color =
  1425. maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
  1426. web_contents()->SetPageBaseBackgroundColor(bg_color);
  1427. SetBackgroundColor(rwhv, bg_color);
  1428. }
  1429. if (!background_throttling_)
  1430. render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
  1431. auto* rwh_impl =
  1432. static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
  1433. if (rwh_impl)
  1434. rwh_impl->disable_hidden_ = !background_throttling_;
  1435. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
  1436. if (web_frame)
  1437. web_frame->MaybeSetupMojoConnection();
  1438. }
  1439. void WebContents::OnBackgroundColorChanged() {
  1440. absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
  1441. if (color.has_value()) {
  1442. auto* const view = web_contents()->GetRenderWidgetHostView();
  1443. static_cast<content::RenderWidgetHostViewBase*>(view)
  1444. ->SetContentBackgroundColor(color.value());
  1445. }
  1446. }
  1447. void WebContents::RenderFrameCreated(
  1448. content::RenderFrameHost* render_frame_host) {
  1449. HandleNewRenderFrame(render_frame_host);
  1450. // RenderFrameCreated is called for speculative frames which may not be
  1451. // used in certain cross-origin navigations. Invoking
  1452. // RenderFrameHost::GetLifecycleState currently crashes when called for
  1453. // speculative frames so we need to filter it out for now. Check
  1454. // https://crbug.com/1183639 for details on when this can be removed.
  1455. auto* rfh_impl =
  1456. static_cast<content::RenderFrameHostImpl*>(render_frame_host);
  1457. if (rfh_impl->lifecycle_state() ==
  1458. content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
  1459. return;
  1460. }
  1461. content::RenderFrameHost::LifecycleState lifecycle_state =
  1462. render_frame_host->GetLifecycleState();
  1463. if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
  1464. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1465. v8::HandleScope handle_scope(isolate);
  1466. gin_helper::Dictionary details =
  1467. gin_helper::Dictionary::CreateEmpty(isolate);
  1468. details.SetGetter("frame", render_frame_host);
  1469. Emit("frame-created", details);
  1470. }
  1471. }
  1472. void WebContents::RenderFrameDeleted(
  1473. content::RenderFrameHost* render_frame_host) {
  1474. // A RenderFrameHost can be deleted when:
  1475. // - A WebContents is removed and its containing frames are disposed.
  1476. // - An <iframe> is removed from the DOM.
  1477. // - Cross-origin navigation creates a new RFH in a separate process which
  1478. // is swapped by content::RenderFrameHostManager.
  1479. //
  1480. // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
  1481. // to find an existing instance of WebFrameMain. During a cross-origin
  1482. // navigation, the deleted RFH will be the old host which was swapped out. In
  1483. // this special case, we need to also ensure that WebFrameMain's internal RFH
  1484. // matches before marking it as disposed.
  1485. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
  1486. if (web_frame && web_frame->render_frame_host() == render_frame_host)
  1487. web_frame->MarkRenderFrameDisposed();
  1488. }
  1489. void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
  1490. content::RenderFrameHost* new_host) {
  1491. if (new_host->IsInPrimaryMainFrame()) {
  1492. if (old_host)
  1493. old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
  1494. if (new_host)
  1495. new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
  1496. }
  1497. // During cross-origin navigation, a FrameTreeNode will swap out its RFH.
  1498. // If an instance of WebFrameMain exists, it will need to have its RFH
  1499. // swapped as well.
  1500. //
  1501. // |old_host| can be a nullptr so we use |new_host| for looking up the
  1502. // WebFrameMain instance.
  1503. auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
  1504. if (web_frame) {
  1505. web_frame->UpdateRenderFrameHost(new_host);
  1506. }
  1507. }
  1508. void WebContents::FrameDeleted(int frame_tree_node_id) {
  1509. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
  1510. if (web_frame)
  1511. web_frame->Destroyed();
  1512. }
  1513. void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
  1514. // This event is necessary for tracking any states with respect to
  1515. // intermediate render view hosts aka speculative render view hosts. Currently
  1516. // used by object-registry.js to ref count remote objects.
  1517. Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
  1518. if (web_contents()->GetRenderViewHost() == render_view_host) {
  1519. // When the RVH that has been deleted is the current RVH it means that the
  1520. // the web contents are being closed. This is communicated by this event.
  1521. // Currently tracked by guest-window-manager.ts to destroy the
  1522. // BrowserWindow.
  1523. Emit("current-render-view-deleted",
  1524. render_view_host->GetProcess()->GetID());
  1525. }
  1526. }
  1527. void WebContents::PrimaryMainFrameRenderProcessGone(
  1528. base::TerminationStatus status) {
  1529. auto weak_this = GetWeakPtr();
  1530. Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
  1531. // User might destroy WebContents in the crashed event.
  1532. if (!weak_this || !web_contents())
  1533. return;
  1534. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1535. v8::HandleScope handle_scope(isolate);
  1536. gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
  1537. details.Set("reason", status);
  1538. details.Set("exitCode", web_contents()->GetCrashedErrorCode());
  1539. Emit("render-process-gone", details);
  1540. }
  1541. void WebContents::PluginCrashed(const base::FilePath& plugin_path,
  1542. base::ProcessId plugin_pid) {
  1543. #if BUILDFLAG(ENABLE_PLUGINS)
  1544. content::WebPluginInfo info;
  1545. auto* plugin_service = content::PluginService::GetInstance();
  1546. plugin_service->GetPluginInfoByPath(plugin_path, &info);
  1547. Emit("plugin-crashed", info.name, info.version);
  1548. #endif // BUILDFLAG(ENABLE_PLUGINS)
  1549. }
  1550. void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
  1551. const content::MediaPlayerId& id) {
  1552. Emit("media-started-playing");
  1553. }
  1554. void WebContents::MediaStoppedPlaying(
  1555. const MediaPlayerInfo& video_type,
  1556. const content::MediaPlayerId& id,
  1557. content::WebContentsObserver::MediaStoppedReason reason) {
  1558. Emit("media-paused");
  1559. }
  1560. void WebContents::DidChangeThemeColor() {
  1561. auto theme_color = web_contents()->GetThemeColor();
  1562. if (theme_color) {
  1563. Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
  1564. } else {
  1565. Emit("did-change-theme-color", nullptr);
  1566. }
  1567. }
  1568. void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
  1569. set_fullscreen_frame(rfh);
  1570. }
  1571. void WebContents::OnWebContentsFocused(
  1572. content::RenderWidgetHost* render_widget_host) {
  1573. Emit("focus");
  1574. }
  1575. void WebContents::OnWebContentsLostFocus(
  1576. content::RenderWidgetHost* render_widget_host) {
  1577. Emit("blur");
  1578. }
  1579. void WebContents::DOMContentLoaded(
  1580. content::RenderFrameHost* render_frame_host) {
  1581. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
  1582. if (web_frame)
  1583. web_frame->DOMContentLoaded();
  1584. if (!render_frame_host->GetParent())
  1585. Emit("dom-ready");
  1586. }
  1587. void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
  1588. const GURL& validated_url) {
  1589. bool is_main_frame = !render_frame_host->GetParent();
  1590. int frame_process_id = render_frame_host->GetProcess()->GetID();
  1591. int frame_routing_id = render_frame_host->GetRoutingID();
  1592. auto weak_this = GetWeakPtr();
  1593. Emit("did-frame-finish-load", is_main_frame, frame_process_id,
  1594. frame_routing_id);
  1595. // ⚠️WARNING!⚠️
  1596. // Emit() triggers JS which can call destroy() on |this|. It's not safe to
  1597. // assume that |this| points to valid memory at this point.
  1598. if (is_main_frame && weak_this && web_contents())
  1599. Emit("did-finish-load");
  1600. }
  1601. void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
  1602. const GURL& url,
  1603. int error_code) {
  1604. // See DocumentLoader::StartLoadingResponse() - when we navigate to a media
  1605. // resource the original request for the media resource, which resulted in a
  1606. // committed navigation, is simply discarded. The media element created
  1607. // inside the MediaDocument then makes *another new* request for the same
  1608. // media resource.
  1609. bool is_media_document =
  1610. media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
  1611. if (error_code == net::ERR_ABORTED && is_media_document)
  1612. return;
  1613. bool is_main_frame = !render_frame_host->GetParent();
  1614. int frame_process_id = render_frame_host->GetProcess()->GetID();
  1615. int frame_routing_id = render_frame_host->GetRoutingID();
  1616. Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
  1617. frame_routing_id);
  1618. }
  1619. void WebContents::DidStartLoading() {
  1620. Emit("did-start-loading");
  1621. }
  1622. void WebContents::DidStopLoading() {
  1623. auto* web_preferences = WebContentsPreferences::From(web_contents());
  1624. if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
  1625. web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
  1626. Emit("did-stop-loading");
  1627. }
  1628. bool WebContents::EmitNavigationEvent(
  1629. const std::string& event_name,
  1630. content::NavigationHandle* navigation_handle) {
  1631. bool is_main_frame = navigation_handle->IsInMainFrame();
  1632. int frame_process_id = -1, frame_routing_id = -1;
  1633. content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
  1634. if (frame_host) {
  1635. frame_process_id = frame_host->GetProcess()->GetID();
  1636. frame_routing_id = frame_host->GetRoutingID();
  1637. }
  1638. bool is_same_document = navigation_handle->IsSameDocument();
  1639. auto url = navigation_handle->GetURL();
  1640. content::RenderFrameHost* initiator_frame_host =
  1641. navigation_handle->GetInitiatorFrameToken().has_value()
  1642. ? content::RenderFrameHost::FromFrameToken(
  1643. navigation_handle->GetInitiatorProcessId(),
  1644. navigation_handle->GetInitiatorFrameToken().value())
  1645. : nullptr;
  1646. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1647. v8::HandleScope handle_scope(isolate);
  1648. gin::Handle<gin_helper::internal::Event> event =
  1649. gin_helper::internal::Event::New(isolate);
  1650. v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
  1651. gin_helper::Dictionary dict(isolate, event_object);
  1652. dict.Set("url", url);
  1653. dict.Set("isSameDocument", is_same_document);
  1654. dict.Set("isMainFrame", is_main_frame);
  1655. dict.Set("frame", frame_host);
  1656. dict.SetGetter("initiator", initiator_frame_host);
  1657. EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
  1658. frame_process_id, frame_routing_id);
  1659. return event->GetDefaultPrevented();
  1660. }
  1661. void WebContents::Message(bool internal,
  1662. const std::string& channel,
  1663. blink::CloneableMessage arguments,
  1664. content::RenderFrameHost* render_frame_host) {
  1665. TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
  1666. // webContents.emit('-ipc-message', new Event(), internal, channel,
  1667. // arguments);
  1668. EmitWithSender("-ipc-message", render_frame_host,
  1669. electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
  1670. channel, std::move(arguments));
  1671. }
  1672. void WebContents::Invoke(
  1673. bool internal,
  1674. const std::string& channel,
  1675. blink::CloneableMessage arguments,
  1676. electron::mojom::ElectronApiIPC::InvokeCallback callback,
  1677. content::RenderFrameHost* render_frame_host) {
  1678. TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
  1679. // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
  1680. EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
  1681. internal, channel, std::move(arguments));
  1682. }
  1683. void WebContents::OnFirstNonEmptyLayout(
  1684. content::RenderFrameHost* render_frame_host) {
  1685. if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
  1686. Emit("ready-to-show");
  1687. }
  1688. }
  1689. // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
  1690. // still call the callback and send an error. Not doing so causes a Mojo DCHECK,
  1691. // since Mojo requires callbacks to be called before they are destroyed.
  1692. class ReplyChannel : public gin::Wrappable<ReplyChannel> {
  1693. public:
  1694. using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
  1695. static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
  1696. InvokeCallback callback) {
  1697. return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
  1698. }
  1699. // gin::Wrappable
  1700. static gin::WrapperInfo kWrapperInfo;
  1701. gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
  1702. v8::Isolate* isolate) override {
  1703. return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
  1704. .SetMethod("sendReply", &ReplyChannel::SendReply);
  1705. }
  1706. const char* GetTypeName() override { return "ReplyChannel"; }
  1707. void SendError(const std::string& msg) {
  1708. v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
  1709. // If there's no current context, it means we're shutting down, so we
  1710. // don't need to send an event.
  1711. if (!isolate->GetCurrentContext().IsEmpty()) {
  1712. v8::HandleScope scope(isolate);
  1713. auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
  1714. SendReply(isolate, message);
  1715. }
  1716. }
  1717. private:
  1718. explicit ReplyChannel(InvokeCallback callback)
  1719. : callback_(std::move(callback)) {}
  1720. ~ReplyChannel() override {
  1721. if (callback_)
  1722. SendError("reply was never sent");
  1723. }
  1724. bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
  1725. if (!callback_)
  1726. return false;
  1727. blink::CloneableMessage message;
  1728. if (!gin::ConvertFromV8(isolate, arg, &message)) {
  1729. return false;
  1730. }
  1731. std::move(callback_).Run(std::move(message));
  1732. return true;
  1733. }
  1734. InvokeCallback callback_;
  1735. };
  1736. gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
  1737. gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
  1738. v8::Isolate* isolate,
  1739. content::RenderFrameHost* frame,
  1740. electron::mojom::ElectronApiIPC::InvokeCallback callback) {
  1741. v8::Local<v8::Object> wrapper;
  1742. if (!GetWrapper(isolate).ToLocal(&wrapper)) {
  1743. if (callback) {
  1744. // We must always invoke the callback if present.
  1745. ReplyChannel::Create(isolate, std::move(callback))
  1746. ->SendError("WebContents was destroyed");
  1747. }
  1748. return gin::Handle<gin_helper::internal::Event>();
  1749. }
  1750. gin::Handle<gin_helper::internal::Event> event =
  1751. gin_helper::internal::Event::New(isolate);
  1752. gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
  1753. if (callback)
  1754. dict.Set("_replyChannel",
  1755. ReplyChannel::Create(isolate, std::move(callback)));
  1756. if (frame) {
  1757. dict.Set("frameId", frame->GetRoutingID());
  1758. dict.Set("processId", frame->GetProcess()->GetID());
  1759. }
  1760. return event;
  1761. }
  1762. void WebContents::ReceivePostMessage(
  1763. const std::string& channel,
  1764. blink::TransferableMessage message,
  1765. content::RenderFrameHost* render_frame_host) {
  1766. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1767. v8::HandleScope handle_scope(isolate);
  1768. auto wrapped_ports =
  1769. MessagePort::EntanglePorts(isolate, std::move(message.ports));
  1770. v8::Local<v8::Value> message_value =
  1771. electron::DeserializeV8Value(isolate, message);
  1772. EmitWithSender("-ipc-ports", render_frame_host,
  1773. electron::mojom::ElectronApiIPC::InvokeCallback(), false,
  1774. channel, message_value, std::move(wrapped_ports));
  1775. }
  1776. void WebContents::MessageSync(
  1777. bool internal,
  1778. const std::string& channel,
  1779. blink::CloneableMessage arguments,
  1780. electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
  1781. content::RenderFrameHost* render_frame_host) {
  1782. TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
  1783. // webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
  1784. // channel, arguments);
  1785. EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
  1786. internal, channel, std::move(arguments));
  1787. }
  1788. void WebContents::MessageTo(int32_t web_contents_id,
  1789. const std::string& channel,
  1790. blink::CloneableMessage arguments,
  1791. content::RenderFrameHost* render_frame_host) {
  1792. TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel);
  1793. auto* target_web_contents = FromID(web_contents_id);
  1794. if (target_web_contents) {
  1795. content::RenderFrameHost* frame = target_web_contents->MainFrame();
  1796. DCHECK(frame);
  1797. v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate());
  1798. gin::Handle<WebFrameMain> web_frame_main =
  1799. WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame);
  1800. if (!web_frame_main->CheckRenderFrame())
  1801. return;
  1802. int32_t sender_id = ID();
  1803. bool sender_is_main_frame = render_frame_host->GetParent() == nullptr;
  1804. web_frame_main->GetRendererApi()->Message(false /* internal */, channel,
  1805. std::move(arguments), sender_id,
  1806. sender_is_main_frame);
  1807. }
  1808. }
  1809. void WebContents::MessageHost(const std::string& channel,
  1810. blink::CloneableMessage arguments,
  1811. content::RenderFrameHost* render_frame_host) {
  1812. TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
  1813. // webContents.emit('ipc-message-host', new Event(), channel, args);
  1814. EmitWithSender("ipc-message-host", render_frame_host,
  1815. electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
  1816. std::move(arguments));
  1817. }
  1818. void WebContents::UpdateDraggableRegions(
  1819. std::vector<mojom::DraggableRegionPtr> regions) {
  1820. if (owner_window() && owner_window()->has_frame())
  1821. return;
  1822. draggable_region_ = DraggableRegionsToSkRegion(regions);
  1823. }
  1824. void WebContents::DidStartNavigation(
  1825. content::NavigationHandle* navigation_handle) {
  1826. EmitNavigationEvent("did-start-navigation", navigation_handle);
  1827. }
  1828. void WebContents::DidRedirectNavigation(
  1829. content::NavigationHandle* navigation_handle) {
  1830. EmitNavigationEvent("did-redirect-navigation", navigation_handle);
  1831. }
  1832. void WebContents::ReadyToCommitNavigation(
  1833. content::NavigationHandle* navigation_handle) {
  1834. // Don't focus content in an inactive window.
  1835. if (!owner_window())
  1836. return;
  1837. #if BUILDFLAG(IS_MAC)
  1838. if (!owner_window()->IsActive())
  1839. return;
  1840. #else
  1841. if (!owner_window()->widget()->IsActive())
  1842. return;
  1843. #endif
  1844. // Don't focus content after subframe navigations.
  1845. if (!navigation_handle->IsInMainFrame())
  1846. return;
  1847. // Only focus for top-level contents.
  1848. if (type_ != Type::kBrowserWindow)
  1849. return;
  1850. web_contents()->SetInitialFocus();
  1851. }
  1852. void WebContents::DidFinishNavigation(
  1853. content::NavigationHandle* navigation_handle) {
  1854. if (owner_window_) {
  1855. owner_window_->NotifyLayoutWindowControlsOverlay();
  1856. }
  1857. if (!navigation_handle->HasCommitted())
  1858. return;
  1859. bool is_main_frame = navigation_handle->IsInMainFrame();
  1860. content::RenderFrameHost* frame_host =
  1861. navigation_handle->GetRenderFrameHost();
  1862. int frame_process_id = -1, frame_routing_id = -1;
  1863. if (frame_host) {
  1864. frame_process_id = frame_host->GetProcess()->GetID();
  1865. frame_routing_id = frame_host->GetRoutingID();
  1866. }
  1867. if (!navigation_handle->IsErrorPage()) {
  1868. // FIXME: All the Emit() calls below could potentially result in |this|
  1869. // being destroyed (by JS listening for the event and calling
  1870. // webContents.destroy()).
  1871. auto url = navigation_handle->GetURL();
  1872. bool is_same_document = navigation_handle->IsSameDocument();
  1873. if (is_same_document) {
  1874. Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
  1875. frame_routing_id);
  1876. } else {
  1877. const net::HttpResponseHeaders* http_response =
  1878. navigation_handle->GetResponseHeaders();
  1879. std::string http_status_text;
  1880. int http_response_code = -1;
  1881. if (http_response) {
  1882. http_status_text = http_response->GetStatusText();
  1883. http_response_code = http_response->response_code();
  1884. }
  1885. Emit("did-frame-navigate", url, http_response_code, http_status_text,
  1886. is_main_frame, frame_process_id, frame_routing_id);
  1887. if (is_main_frame) {
  1888. Emit("did-navigate", url, http_response_code, http_status_text);
  1889. }
  1890. }
  1891. if (IsGuest())
  1892. Emit("load-commit", url, is_main_frame);
  1893. } else {
  1894. auto url = navigation_handle->GetURL();
  1895. int code = navigation_handle->GetNetErrorCode();
  1896. auto description = net::ErrorToShortString(code);
  1897. Emit("did-fail-provisional-load", code, description, url, is_main_frame,
  1898. frame_process_id, frame_routing_id);
  1899. // Do not emit "did-fail-load" for canceled requests.
  1900. if (code != net::ERR_ABORTED) {
  1901. EmitWarning(
  1902. node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
  1903. "Failed to load URL: " + url.possibly_invalid_spec() +
  1904. " with error: " + description,
  1905. "electron");
  1906. Emit("did-fail-load", code, description, url, is_main_frame,
  1907. frame_process_id, frame_routing_id);
  1908. }
  1909. }
  1910. content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
  1911. // This check is needed due to an issue in Chromium
  1912. // Check the Chromium issue to keep updated:
  1913. // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
  1914. // If a history entry has been made and the forward/back call has been made,
  1915. // proceed with setting the new title
  1916. if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
  1917. WebContents::TitleWasSet(entry);
  1918. }
  1919. void WebContents::TitleWasSet(content::NavigationEntry* entry) {
  1920. std::u16string final_title;
  1921. bool explicit_set = true;
  1922. if (entry) {
  1923. auto title = entry->GetTitle();
  1924. auto url = entry->GetURL();
  1925. if (url.SchemeIsFile() && title.empty()) {
  1926. final_title = base::UTF8ToUTF16(url.ExtractFileName());
  1927. explicit_set = false;
  1928. } else {
  1929. final_title = title;
  1930. }
  1931. } else {
  1932. final_title = web_contents()->GetTitle();
  1933. }
  1934. for (ExtendedWebContentsObserver& observer : observers_)
  1935. observer.OnPageTitleUpdated(final_title, explicit_set);
  1936. Emit("page-title-updated", final_title, explicit_set);
  1937. }
  1938. void WebContents::DidUpdateFaviconURL(
  1939. content::RenderFrameHost* render_frame_host,
  1940. const std::vector<blink::mojom::FaviconURLPtr>& urls) {
  1941. std::set<GURL> unique_urls;
  1942. for (const auto& iter : urls) {
  1943. if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
  1944. continue;
  1945. const GURL& url = iter->icon_url;
  1946. if (url.is_valid())
  1947. unique_urls.insert(url);
  1948. }
  1949. Emit("page-favicon-updated", unique_urls);
  1950. }
  1951. void WebContents::DevToolsReloadPage() {
  1952. Emit("devtools-reload-page");
  1953. }
  1954. void WebContents::DevToolsFocused() {
  1955. Emit("devtools-focused");
  1956. }
  1957. void WebContents::DevToolsOpened() {
  1958. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1959. v8::HandleScope handle_scope(isolate);
  1960. DCHECK(inspectable_web_contents_);
  1961. DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
  1962. auto handle = FromOrCreate(
  1963. isolate, inspectable_web_contents_->GetDevToolsWebContents());
  1964. devtools_web_contents_.Reset(isolate, handle.ToV8());
  1965. // Set inspected tabID.
  1966. inspectable_web_contents_->CallClientFunction(
  1967. "DevToolsAPI", "setInspectedTabId", base::Value(ID()));
  1968. // Inherit owner window in devtools when it doesn't have one.
  1969. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
  1970. bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
  1971. if (owner_window() && !has_window)
  1972. handle->SetOwnerWindow(devtools, owner_window());
  1973. Emit("devtools-opened");
  1974. }
  1975. void WebContents::DevToolsClosed() {
  1976. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1977. v8::HandleScope handle_scope(isolate);
  1978. devtools_web_contents_.Reset();
  1979. Emit("devtools-closed");
  1980. }
  1981. void WebContents::DevToolsResized() {
  1982. for (ExtendedWebContentsObserver& observer : observers_)
  1983. observer.OnDevToolsResized();
  1984. }
  1985. void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
  1986. SetOwnerWindow(GetWebContents(), owner_window);
  1987. }
  1988. void WebContents::SetOwnerWindow(content::WebContents* web_contents,
  1989. NativeWindow* owner_window) {
  1990. if (owner_window) {
  1991. owner_window_ = owner_window->GetWeakPtr();
  1992. NativeWindowRelay::CreateForWebContents(web_contents,
  1993. owner_window->GetWeakPtr());
  1994. } else {
  1995. owner_window_ = nullptr;
  1996. web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
  1997. }
  1998. auto* osr_wcv = GetOffScreenWebContentsView();
  1999. if (osr_wcv)
  2000. osr_wcv->SetNativeWindow(owner_window);
  2001. }
  2002. content::WebContents* WebContents::GetWebContents() const {
  2003. if (!inspectable_web_contents_)
  2004. return nullptr;
  2005. return inspectable_web_contents_->GetWebContents();
  2006. }
  2007. content::WebContents* WebContents::GetDevToolsWebContents() const {
  2008. if (!inspectable_web_contents_)
  2009. return nullptr;
  2010. return inspectable_web_contents_->GetDevToolsWebContents();
  2011. }
  2012. void WebContents::WebContentsDestroyed() {
  2013. // Clear the pointer stored in wrapper.
  2014. if (GetAllWebContents().Lookup(id_))
  2015. GetAllWebContents().Remove(id_);
  2016. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  2017. v8::HandleScope scope(isolate);
  2018. v8::Local<v8::Object> wrapper;
  2019. if (!GetWrapper(isolate).ToLocal(&wrapper))
  2020. return;
  2021. wrapper->SetAlignedPointerInInternalField(0, nullptr);
  2022. // Tell WebViewGuestDelegate that the WebContents has been destroyed.
  2023. if (guest_delegate_)
  2024. guest_delegate_->WillDestroy();
  2025. Observe(nullptr);
  2026. Emit("destroyed");
  2027. }
  2028. void WebContents::NavigationEntryCommitted(
  2029. const content::LoadCommittedDetails& details) {
  2030. Emit("navigation-entry-committed", details.entry->GetURL(),
  2031. details.is_same_document, details.did_replace_entry);
  2032. }
  2033. bool WebContents::GetBackgroundThrottling() const {
  2034. return background_throttling_;
  2035. }
  2036. void WebContents::SetBackgroundThrottling(bool allowed) {
  2037. background_throttling_ = allowed;
  2038. auto* rfh = web_contents()->GetPrimaryMainFrame();
  2039. if (!rfh)
  2040. return;
  2041. auto* rwhv = rfh->GetView();
  2042. if (!rwhv)
  2043. return;
  2044. auto* rwh_impl =
  2045. static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
  2046. if (!rwh_impl)
  2047. return;
  2048. rwh_impl->disable_hidden_ = !background_throttling_;
  2049. web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
  2050. if (rwh_impl->is_hidden()) {
  2051. rwh_impl->WasShown({});
  2052. }
  2053. }
  2054. int WebContents::GetProcessID() const {
  2055. return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  2056. }
  2057. base::ProcessId WebContents::GetOSProcessID() const {
  2058. base::ProcessHandle process_handle = web_contents()
  2059. ->GetPrimaryMainFrame()
  2060. ->GetProcess()
  2061. ->GetProcess()
  2062. .Handle();
  2063. return base::GetProcId(process_handle);
  2064. }
  2065. WebContents::Type WebContents::GetType() const {
  2066. return type_;
  2067. }
  2068. bool WebContents::Equal(const WebContents* web_contents) const {
  2069. return ID() == web_contents->ID();
  2070. }
  2071. GURL WebContents::GetURL() const {
  2072. return web_contents()->GetLastCommittedURL();
  2073. }
  2074. void WebContents::LoadURL(const GURL& url,
  2075. const gin_helper::Dictionary& options) {
  2076. if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
  2077. Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
  2078. net::ErrorToShortString(net::ERR_INVALID_URL),
  2079. url.possibly_invalid_spec(), true);
  2080. return;
  2081. }
  2082. content::NavigationController::LoadURLParams params(url);
  2083. if (!options.Get("httpReferrer", &params.referrer)) {
  2084. GURL http_referrer;
  2085. if (options.Get("httpReferrer", &http_referrer))
  2086. params.referrer =
  2087. content::Referrer(http_referrer.GetAsReferrer(),
  2088. network::mojom::ReferrerPolicy::kDefault);
  2089. }
  2090. std::string user_agent;
  2091. if (options.Get("userAgent", &user_agent))
  2092. SetUserAgent(user_agent);
  2093. std::string extra_headers;
  2094. if (options.Get("extraHeaders", &extra_headers))
  2095. params.extra_headers = extra_headers;
  2096. scoped_refptr<network::ResourceRequestBody> body;
  2097. if (options.Get("postData", &body)) {
  2098. params.post_data = body;
  2099. params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
  2100. }
  2101. GURL base_url_for_data_url;
  2102. if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
  2103. params.base_url_for_data_url = base_url_for_data_url;
  2104. params.load_type = content::NavigationController::LOAD_TYPE_DATA;
  2105. }
  2106. bool reload_ignoring_cache = false;
  2107. if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
  2108. reload_ignoring_cache) {
  2109. params.reload_type = content::ReloadType::BYPASSING_CACHE;
  2110. }
  2111. // Calling LoadURLWithParams() can trigger JS which destroys |this|.
  2112. auto weak_this = GetWeakPtr();
  2113. params.transition_type = ui::PageTransitionFromInt(
  2114. ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
  2115. params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
  2116. // Discard non-committed entries to ensure that we don't re-use a pending
  2117. // entry
  2118. web_contents()->GetController().DiscardNonCommittedEntries();
  2119. web_contents()->GetController().LoadURLWithParams(params);
  2120. // ⚠️WARNING!⚠️
  2121. // LoadURLWithParams() triggers JS events which can call destroy() on |this|.
  2122. // It's not safe to assume that |this| points to valid memory at this point.
  2123. if (!weak_this || !web_contents())
  2124. return;
  2125. // Required to make beforeunload handler work.
  2126. NotifyUserActivation();
  2127. }
  2128. // TODO(MarshallOfSound): Figure out what we need to do with post data here, I
  2129. // believe the default behavior when we pass "true" is to phone out to the
  2130. // delegate and then the controller expects this method to be called again with
  2131. // "false" if the user approves the reload. For now this would result in
  2132. // ".reload()" calls on POST data domains failing silently. Passing false would
  2133. // result in them succeeding, but reposting which although more correct could be
  2134. // considering a breaking change.
  2135. void WebContents::Reload() {
  2136. web_contents()->GetController().Reload(content::ReloadType::NORMAL,
  2137. /* check_for_repost */ true);
  2138. }
  2139. void WebContents::ReloadIgnoringCache() {
  2140. web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
  2141. /* check_for_repost */ true);
  2142. }
  2143. void WebContents::DownloadURL(const GURL& url) {
  2144. auto* browser_context = web_contents()->GetBrowserContext();
  2145. auto* download_manager = browser_context->GetDownloadManager();
  2146. std::unique_ptr<download::DownloadUrlParameters> download_params(
  2147. content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
  2148. web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
  2149. download_manager->DownloadUrl(std::move(download_params));
  2150. }
  2151. std::u16string WebContents::GetTitle() const {
  2152. return web_contents()->GetTitle();
  2153. }
  2154. bool WebContents::IsLoading() const {
  2155. return web_contents()->IsLoading();
  2156. }
  2157. bool WebContents::IsLoadingMainFrame() const {
  2158. return web_contents()->ShouldShowLoadingUI();
  2159. }
  2160. bool WebContents::IsWaitingForResponse() const {
  2161. return web_contents()->IsWaitingForResponse();
  2162. }
  2163. void WebContents::Stop() {
  2164. web_contents()->Stop();
  2165. }
  2166. bool WebContents::CanGoBack() const {
  2167. return web_contents()->GetController().CanGoBack();
  2168. }
  2169. void WebContents::GoBack() {
  2170. if (CanGoBack())
  2171. web_contents()->GetController().GoBack();
  2172. }
  2173. bool WebContents::CanGoForward() const {
  2174. return web_contents()->GetController().CanGoForward();
  2175. }
  2176. void WebContents::GoForward() {
  2177. if (CanGoForward())
  2178. web_contents()->GetController().GoForward();
  2179. }
  2180. bool WebContents::CanGoToOffset(int offset) const {
  2181. return web_contents()->GetController().CanGoToOffset(offset);
  2182. }
  2183. void WebContents::GoToOffset(int offset) {
  2184. if (CanGoToOffset(offset))
  2185. web_contents()->GetController().GoToOffset(offset);
  2186. }
  2187. bool WebContents::CanGoToIndex(int index) const {
  2188. return index >= 0 && index < GetHistoryLength();
  2189. }
  2190. void WebContents::GoToIndex(int index) {
  2191. if (CanGoToIndex(index))
  2192. web_contents()->GetController().GoToIndex(index);
  2193. }
  2194. int WebContents::GetActiveIndex() const {
  2195. return web_contents()->GetController().GetCurrentEntryIndex();
  2196. }
  2197. void WebContents::ClearHistory() {
  2198. // In some rare cases (normally while there is no real history) we are in a
  2199. // state where we can't prune navigation entries
  2200. if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
  2201. web_contents()->GetController().PruneAllButLastCommitted();
  2202. }
  2203. }
  2204. int WebContents::GetHistoryLength() const {
  2205. return web_contents()->GetController().GetEntryCount();
  2206. }
  2207. const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
  2208. return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
  2209. }
  2210. void WebContents::SetWebRTCIPHandlingPolicy(
  2211. const std::string& webrtc_ip_handling_policy) {
  2212. if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
  2213. return;
  2214. web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
  2215. webrtc_ip_handling_policy;
  2216. web_contents()->SyncRendererPrefs();
  2217. }
  2218. std::string WebContents::GetMediaSourceID(
  2219. content::WebContents* request_web_contents) {
  2220. auto* frame_host = web_contents()->GetPrimaryMainFrame();
  2221. if (!frame_host)
  2222. return std::string();
  2223. content::DesktopMediaID media_id(
  2224. content::DesktopMediaID::TYPE_WEB_CONTENTS,
  2225. content::DesktopMediaID::kNullId,
  2226. content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
  2227. frame_host->GetRoutingID()));
  2228. auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
  2229. if (!request_frame_host)
  2230. return std::string();
  2231. std::string id =
  2232. content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
  2233. request_frame_host->GetProcess()->GetID(),
  2234. request_frame_host->GetRoutingID(),
  2235. url::Origin::Create(request_frame_host->GetLastCommittedURL()
  2236. .DeprecatedGetOriginAsURL()),
  2237. media_id, content::kRegistryStreamTypeTab);
  2238. return id;
  2239. }
  2240. bool WebContents::IsCrashed() const {
  2241. return web_contents()->IsCrashed();
  2242. }
  2243. void WebContents::ForcefullyCrashRenderer() {
  2244. content::RenderWidgetHostView* view =
  2245. web_contents()->GetRenderWidgetHostView();
  2246. if (!view)
  2247. return;
  2248. content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
  2249. if (!rwh)
  2250. return;
  2251. content::RenderProcessHost* rph = rwh->GetProcess();
  2252. if (rph) {
  2253. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  2254. // A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
  2255. // Instead we send an explicit IPC to crash on the renderer's IO thread.
  2256. rph->ForceCrash();
  2257. #else
  2258. // Try to generate a crash report for the hung process.
  2259. #if !IS_MAS_BUILD()
  2260. CrashDumpHungChildProcess(rph->GetProcess().Handle());
  2261. #endif
  2262. rph->Shutdown(content::RESULT_CODE_HUNG);
  2263. #endif
  2264. }
  2265. }
  2266. void WebContents::SetUserAgent(const std::string& user_agent) {
  2267. blink::UserAgentOverride ua_override;
  2268. ua_override.ua_string_override = user_agent;
  2269. if (!user_agent.empty())
  2270. ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
  2271. web_contents()->SetUserAgentOverride(ua_override, false);
  2272. }
  2273. std::string WebContents::GetUserAgent() {
  2274. return web_contents()->GetUserAgentOverride().ua_string_override;
  2275. }
  2276. v8::Local<v8::Promise> WebContents::SavePage(
  2277. const base::FilePath& full_file_path,
  2278. const content::SavePageType& save_type) {
  2279. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  2280. gin_helper::Promise<void> promise(isolate);
  2281. v8::Local<v8::Promise> handle = promise.GetHandle();
  2282. if (!full_file_path.IsAbsolute()) {
  2283. promise.RejectWithErrorMessage("Path must be absolute");
  2284. return handle;
  2285. }
  2286. auto* handler = new SavePageHandler(web_contents(), std::move(promise));
  2287. handler->Handle(full_file_path, save_type);
  2288. return handle;
  2289. }
  2290. void WebContents::OpenDevTools(gin::Arguments* args) {
  2291. if (type_ == Type::kRemote)
  2292. return;
  2293. if (!enable_devtools_)
  2294. return;
  2295. std::string state;
  2296. if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
  2297. !owner_window()) {
  2298. state = "detach";
  2299. }
  2300. #if BUILDFLAG(IS_WIN)
  2301. auto* win = static_cast<NativeWindowViews*>(owner_window());
  2302. // Force a detached state when WCO is enabled to match Chrome
  2303. // behavior and prevent occlusion of DevTools.
  2304. if (win && win->IsWindowControlsOverlayEnabled())
  2305. state = "detach";
  2306. #endif
  2307. bool activate = true;
  2308. std::string title;
  2309. if (args && args->Length() == 1) {
  2310. gin_helper::Dictionary options;
  2311. if (args->GetNext(&options)) {
  2312. options.Get("mode", &state);
  2313. options.Get("activate", &activate);
  2314. options.Get("title", &title);
  2315. }
  2316. }
  2317. DCHECK(inspectable_web_contents_);
  2318. inspectable_web_contents_->SetDockState(state);
  2319. inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title));
  2320. inspectable_web_contents_->ShowDevTools(activate);
  2321. }
  2322. void WebContents::CloseDevTools() {
  2323. if (type_ == Type::kRemote)
  2324. return;
  2325. DCHECK(inspectable_web_contents_);
  2326. inspectable_web_contents_->CloseDevTools();
  2327. }
  2328. bool WebContents::IsDevToolsOpened() {
  2329. if (type_ == Type::kRemote)
  2330. return false;
  2331. DCHECK(inspectable_web_contents_);
  2332. return inspectable_web_contents_->IsDevToolsViewShowing();
  2333. }
  2334. std::u16string WebContents::GetDevToolsTitle() {
  2335. if (type_ == Type::kRemote)
  2336. return std::u16string();
  2337. DCHECK(inspectable_web_contents_);
  2338. return inspectable_web_contents_->GetDevToolsTitle();
  2339. }
  2340. void WebContents::SetDevToolsTitle(const std::u16string& title) {
  2341. inspectable_web_contents_->SetDevToolsTitle(title);
  2342. }
  2343. bool WebContents::IsDevToolsFocused() {
  2344. if (type_ == Type::kRemote)
  2345. return false;
  2346. DCHECK(inspectable_web_contents_);
  2347. return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
  2348. }
  2349. void WebContents::EnableDeviceEmulation(
  2350. const blink::DeviceEmulationParams& params) {
  2351. if (type_ == Type::kRemote)
  2352. return;
  2353. DCHECK(web_contents());
  2354. auto* frame_host = web_contents()->GetPrimaryMainFrame();
  2355. if (frame_host) {
  2356. auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
  2357. frame_host->GetView()->GetRenderWidgetHost());
  2358. if (widget_host_impl) {
  2359. auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
  2360. frame_widget->EnableDeviceEmulation(params);
  2361. }
  2362. }
  2363. }
  2364. void WebContents::DisableDeviceEmulation() {
  2365. if (type_ == Type::kRemote)
  2366. return;
  2367. DCHECK(web_contents());
  2368. auto* frame_host = web_contents()->GetPrimaryMainFrame();
  2369. if (frame_host) {
  2370. auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
  2371. frame_host->GetView()->GetRenderWidgetHost());
  2372. if (widget_host_impl) {
  2373. auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
  2374. frame_widget->DisableDeviceEmulation();
  2375. }
  2376. }
  2377. }
  2378. void WebContents::ToggleDevTools() {
  2379. if (IsDevToolsOpened())
  2380. CloseDevTools();
  2381. else
  2382. OpenDevTools(nullptr);
  2383. }
  2384. void WebContents::InspectElement(int x, int y) {
  2385. if (type_ == Type::kRemote)
  2386. return;
  2387. if (!enable_devtools_)
  2388. return;
  2389. DCHECK(inspectable_web_contents_);
  2390. if (!inspectable_web_contents_->GetDevToolsWebContents())
  2391. OpenDevTools(nullptr);
  2392. inspectable_web_contents_->InspectElement(x, y);
  2393. }
  2394. void WebContents::InspectSharedWorkerById(const std::string& workerId) {
  2395. if (type_ == Type::kRemote)
  2396. return;
  2397. if (!enable_devtools_)
  2398. return;
  2399. for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
  2400. if (agent_host->GetType() ==
  2401. content::DevToolsAgentHost::kTypeSharedWorker) {
  2402. if (agent_host->GetId() == workerId) {
  2403. OpenDevTools(nullptr);
  2404. inspectable_web_contents_->AttachTo(agent_host);
  2405. break;
  2406. }
  2407. }
  2408. }
  2409. }
  2410. std::vector<scoped_refptr<content::DevToolsAgentHost>>
  2411. WebContents::GetAllSharedWorkers() {
  2412. std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
  2413. if (type_ == Type::kRemote)
  2414. return shared_workers;
  2415. if (!enable_devtools_)
  2416. return shared_workers;
  2417. for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
  2418. if (agent_host->GetType() ==
  2419. content::DevToolsAgentHost::kTypeSharedWorker) {
  2420. shared_workers.push_back(agent_host);
  2421. }
  2422. }
  2423. return shared_workers;
  2424. }
  2425. void WebContents::InspectSharedWorker() {
  2426. if (type_ == Type::kRemote)
  2427. return;
  2428. if (!enable_devtools_)
  2429. return;
  2430. for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
  2431. if (agent_host->GetType() ==
  2432. content::DevToolsAgentHost::kTypeSharedWorker) {
  2433. OpenDevTools(nullptr);
  2434. inspectable_web_contents_->AttachTo(agent_host);
  2435. break;
  2436. }
  2437. }
  2438. }
  2439. void WebContents::InspectServiceWorker() {
  2440. if (type_ == Type::kRemote)
  2441. return;
  2442. if (!enable_devtools_)
  2443. return;
  2444. for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
  2445. if (agent_host->GetType() ==
  2446. content::DevToolsAgentHost::kTypeServiceWorker) {
  2447. OpenDevTools(nullptr);
  2448. inspectable_web_contents_->AttachTo(agent_host);
  2449. break;
  2450. }
  2451. }
  2452. }
  2453. void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
  2454. auto* web_preferences = WebContentsPreferences::From(web_contents());
  2455. DCHECK(web_preferences);
  2456. web_preferences->SetIgnoreMenuShortcuts(ignore);
  2457. }
  2458. void WebContents::SetAudioMuted(bool muted) {
  2459. web_contents()->SetAudioMuted(muted);
  2460. }
  2461. bool WebContents::IsAudioMuted() {
  2462. return web_contents()->IsAudioMuted();
  2463. }
  2464. bool WebContents::IsCurrentlyAudible() {
  2465. return web_contents()->IsCurrentlyAudible();
  2466. }
  2467. #if BUILDFLAG(ENABLE_PRINTING)
  2468. void WebContents::OnGetDeviceNameToUse(
  2469. base::Value::Dict print_settings,
  2470. printing::CompletionCallback print_callback,
  2471. bool silent,
  2472. // <error, device_name>
  2473. std::pair<std::string, std::u16string> info) {
  2474. // The content::WebContents might be already deleted at this point, and the
  2475. // PrintViewManagerElectron class does not do null check.
  2476. if (!web_contents()) {
  2477. if (print_callback)
  2478. std::move(print_callback).Run(false, "failed");
  2479. return;
  2480. }
  2481. if (!info.first.empty()) {
  2482. if (print_callback)
  2483. std::move(print_callback).Run(false, info.first);
  2484. return;
  2485. }
  2486. // If the user has passed a deviceName use it, otherwise use default printer.
  2487. print_settings.Set(printing::kSettingDeviceName, info.second);
  2488. auto* print_view_manager =
  2489. PrintViewManagerElectron::FromWebContents(web_contents());
  2490. if (!print_view_manager)
  2491. return;
  2492. auto* focused_frame = web_contents()->GetFocusedFrame();
  2493. auto* rfh = focused_frame && focused_frame->HasSelection()
  2494. ? focused_frame
  2495. : web_contents()->GetPrimaryMainFrame();
  2496. print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
  2497. std::move(print_callback));
  2498. }
  2499. void WebContents::Print(gin::Arguments* args) {
  2500. gin_helper::Dictionary options =
  2501. gin::Dictionary::CreateEmpty(args->isolate());
  2502. base::Value::Dict settings;
  2503. if (args->Length() >= 1 && !args->GetNext(&options)) {
  2504. gin_helper::ErrorThrower(args->isolate())
  2505. .ThrowError("webContents.print(): Invalid print settings specified.");
  2506. return;
  2507. }
  2508. printing::CompletionCallback callback;
  2509. if (args->Length() == 2 && !args->GetNext(&callback)) {
  2510. gin_helper::ErrorThrower(args->isolate())
  2511. .ThrowError("webContents.print(): Invalid optional callback provided.");
  2512. return;
  2513. }
  2514. // Set optional silent printing
  2515. bool silent = false;
  2516. options.Get("silent", &silent);
  2517. bool print_background = false;
  2518. options.Get("printBackground", &print_background);
  2519. settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
  2520. // Set custom margin settings
  2521. gin_helper::Dictionary margins =
  2522. gin::Dictionary::CreateEmpty(args->isolate());
  2523. if (options.Get("margins", &margins)) {
  2524. printing::mojom::MarginType margin_type =
  2525. printing::mojom::MarginType::kDefaultMargins;
  2526. margins.Get("marginType", &margin_type);
  2527. settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
  2528. if (margin_type == printing::mojom::MarginType::kCustomMargins) {
  2529. base::Value::Dict custom_margins;
  2530. int top = 0;
  2531. margins.Get("top", &top);
  2532. custom_margins.Set(printing::kSettingMarginTop, top);
  2533. int bottom = 0;
  2534. margins.Get("bottom", &bottom);
  2535. custom_margins.Set(printing::kSettingMarginBottom, bottom);
  2536. int left = 0;
  2537. margins.Get("left", &left);
  2538. custom_margins.Set(printing::kSettingMarginLeft, left);
  2539. int right = 0;
  2540. margins.Get("right", &right);
  2541. custom_margins.Set(printing::kSettingMarginRight, right);
  2542. settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
  2543. }
  2544. } else {
  2545. settings.Set(
  2546. printing::kSettingMarginsType,
  2547. static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
  2548. }
  2549. // Set whether to print color or greyscale
  2550. bool print_color = true;
  2551. options.Get("color", &print_color);
  2552. auto const color_model = print_color ? printing::mojom::ColorModel::kColor
  2553. : printing::mojom::ColorModel::kGray;
  2554. settings.Set(printing::kSettingColor, static_cast<int>(color_model));
  2555. // Is the orientation landscape or portrait.
  2556. bool landscape = false;
  2557. options.Get("landscape", &landscape);
  2558. settings.Set(printing::kSettingLandscape, landscape);
  2559. // We set the default to the system's default printer and only update
  2560. // if at the Chromium level if the user overrides.
  2561. // Printer device name as opened by the OS.
  2562. std::u16string device_name;
  2563. options.Get("deviceName", &device_name);
  2564. int scale_factor = 100;
  2565. options.Get("scaleFactor", &scale_factor);
  2566. settings.Set(printing::kSettingScaleFactor, scale_factor);
  2567. int pages_per_sheet = 1;
  2568. options.Get("pagesPerSheet", &pages_per_sheet);
  2569. settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
  2570. // True if the user wants to print with collate.
  2571. bool collate = true;
  2572. options.Get("collate", &collate);
  2573. settings.Set(printing::kSettingCollate, collate);
  2574. // The number of individual copies to print
  2575. int copies = 1;
  2576. options.Get("copies", &copies);
  2577. settings.Set(printing::kSettingCopies, copies);
  2578. // Strings to be printed as headers and footers if requested by the user.
  2579. std::string header;
  2580. options.Get("header", &header);
  2581. std::string footer;
  2582. options.Get("footer", &footer);
  2583. if (!(header.empty() && footer.empty())) {
  2584. settings.Set(printing::kSettingHeaderFooterEnabled, true);
  2585. settings.Set(printing::kSettingHeaderFooterTitle, header);
  2586. settings.Set(printing::kSettingHeaderFooterURL, footer);
  2587. } else {
  2588. settings.Set(printing::kSettingHeaderFooterEnabled, false);
  2589. }
  2590. // We don't want to allow the user to enable these settings
  2591. // but we need to set them or a CHECK is hit.
  2592. settings.Set(printing::kSettingPrinterType,
  2593. static_cast<int>(printing::mojom::PrinterType::kLocal));
  2594. settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
  2595. settings.Set(printing::kSettingRasterizePdf, false);
  2596. // Set custom page ranges to print
  2597. std::vector<gin_helper::Dictionary> page_ranges;
  2598. if (options.Get("pageRanges", &page_ranges)) {
  2599. base::Value::List page_range_list;
  2600. for (auto& range : page_ranges) {
  2601. int from, to;
  2602. if (range.Get("from", &from) && range.Get("to", &to)) {
  2603. base::Value::Dict range_dict;
  2604. // Chromium uses 1-based page ranges, so increment each by 1.
  2605. range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
  2606. range_dict.Set(printing::kSettingPageRangeTo, to + 1);
  2607. page_range_list.Append(std::move(range_dict));
  2608. } else {
  2609. continue;
  2610. }
  2611. }
  2612. if (!page_range_list.empty())
  2613. settings.Set(printing::kSettingPageRange, std::move(page_range_list));
  2614. }
  2615. // Duplex type user wants to use.
  2616. printing::mojom::DuplexMode duplex_mode =
  2617. printing::mojom::DuplexMode::kSimplex;
  2618. options.Get("duplexMode", &duplex_mode);
  2619. settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
  2620. // We've already done necessary parameter sanitization at the
  2621. // JS level, so we can simply pass this through.
  2622. base::Value media_size(base::Value::Type::DICT);
  2623. if (options.Get("mediaSize", &media_size))
  2624. settings.Set(printing::kSettingMediaSize, std::move(media_size));
  2625. // Set custom dots per inch (dpi)
  2626. gin_helper::Dictionary dpi_settings;
  2627. int dpi = 72;
  2628. if (options.Get("dpi", &dpi_settings)) {
  2629. int horizontal = 72;
  2630. dpi_settings.Get("horizontal", &horizontal);
  2631. settings.Set(printing::kSettingDpiHorizontal, horizontal);
  2632. int vertical = 72;
  2633. dpi_settings.Get("vertical", &vertical);
  2634. settings.Set(printing::kSettingDpiVertical, vertical);
  2635. } else {
  2636. settings.Set(printing::kSettingDpiHorizontal, dpi);
  2637. settings.Set(printing::kSettingDpiVertical, dpi);
  2638. }
  2639. print_task_runner_->PostTaskAndReplyWithResult(
  2640. FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
  2641. base::BindOnce(&WebContents::OnGetDeviceNameToUse,
  2642. weak_factory_.GetWeakPtr(), std::move(settings),
  2643. std::move(callback), silent));
  2644. }
  2645. // Partially duplicated and modified from
  2646. // headless/lib/browser/protocol/page_handler.cc;l=41
  2647. v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
  2648. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  2649. gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
  2650. v8::Local<v8::Promise> handle = promise.GetHandle();
  2651. // This allows us to track headless printing calls.
  2652. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
  2653. auto landscape = settings.GetDict().FindBool("landscape");
  2654. auto display_header_footer =
  2655. settings.GetDict().FindBool("displayHeaderFooter");
  2656. auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
  2657. auto scale = settings.GetDict().FindDouble("scale");
  2658. auto paper_width = settings.GetDict().FindDouble("paperWidth");
  2659. auto paper_height = settings.GetDict().FindDouble("paperHeight");
  2660. auto margin_top = settings.GetDict().FindDouble("marginTop");
  2661. auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
  2662. auto margin_left = settings.GetDict().FindDouble("marginLeft");
  2663. auto margin_right = settings.GetDict().FindDouble("marginRight");
  2664. auto page_ranges = *settings.GetDict().FindString("pageRanges");
  2665. auto header_template = *settings.GetDict().FindString("headerTemplate");
  2666. auto footer_template = *settings.GetDict().FindString("footerTemplate");
  2667. auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
  2668. auto generate_tagged_pdf =
  2669. settings.GetDict().FindBool("shouldGenerateTaggedPDF");
  2670. absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
  2671. print_pages_params = print_to_pdf::GetPrintPagesParams(
  2672. web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
  2673. landscape, display_header_footer, print_background, scale,
  2674. paper_width, paper_height, margin_top, margin_bottom, margin_left,
  2675. margin_right, absl::make_optional(header_template),
  2676. absl::make_optional(footer_template), prefer_css_page_size,
  2677. generate_tagged_pdf);
  2678. if (absl::holds_alternative<std::string>(print_pages_params)) {
  2679. auto error = absl::get<std::string>(print_pages_params);
  2680. promise.RejectWithErrorMessage("Invalid print parameters: " + error);
  2681. return handle;
  2682. }
  2683. auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
  2684. if (!manager) {
  2685. promise.RejectWithErrorMessage("Failed to find print manager");
  2686. return handle;
  2687. }
  2688. auto params = std::move(
  2689. absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
  2690. params->params->document_cookie = unique_id.value_or(0);
  2691. manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
  2692. std::move(params),
  2693. base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
  2694. std::move(promise)));
  2695. return handle;
  2696. }
  2697. void WebContents::OnPDFCreated(
  2698. gin_helper::Promise<v8::Local<v8::Value>> promise,
  2699. print_to_pdf::PdfPrintResult print_result,
  2700. scoped_refptr<base::RefCountedMemory> data) {
  2701. if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
  2702. promise.RejectWithErrorMessage(
  2703. "Failed to generate PDF: " +
  2704. print_to_pdf::PdfPrintResultToString(print_result));
  2705. return;
  2706. }
  2707. v8::Isolate* isolate = promise.isolate();
  2708. gin_helper::Locker locker(isolate);
  2709. v8::HandleScope handle_scope(isolate);
  2710. v8::Context::Scope context_scope(
  2711. v8::Local<v8::Context>::New(isolate, promise.GetContext()));
  2712. v8::Local<v8::Value> buffer =
  2713. node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
  2714. data->size())
  2715. .ToLocalChecked();
  2716. promise.Resolve(buffer);
  2717. }
  2718. #endif
  2719. void WebContents::AddWorkSpace(gin::Arguments* args,
  2720. const base::FilePath& path) {
  2721. if (path.empty()) {
  2722. gin_helper::ErrorThrower(args->isolate())
  2723. .ThrowError("path cannot be empty");
  2724. return;
  2725. }
  2726. DevToolsAddFileSystem(std::string(), path);
  2727. }
  2728. void WebContents::RemoveWorkSpace(gin::Arguments* args,
  2729. const base::FilePath& path) {
  2730. if (path.empty()) {
  2731. gin_helper::ErrorThrower(args->isolate())
  2732. .ThrowError("path cannot be empty");
  2733. return;
  2734. }
  2735. DevToolsRemoveFileSystem(path);
  2736. }
  2737. void WebContents::Undo() {
  2738. web_contents()->Undo();
  2739. }
  2740. void WebContents::Redo() {
  2741. web_contents()->Redo();
  2742. }
  2743. void WebContents::Cut() {
  2744. web_contents()->Cut();
  2745. }
  2746. void WebContents::Copy() {
  2747. web_contents()->Copy();
  2748. }
  2749. void WebContents::CenterSelection() {
  2750. web_contents()->CenterSelection();
  2751. }
  2752. void WebContents::Paste() {
  2753. web_contents()->Paste();
  2754. }
  2755. void WebContents::PasteAndMatchStyle() {
  2756. web_contents()->PasteAndMatchStyle();
  2757. }
  2758. void WebContents::Delete() {
  2759. web_contents()->Delete();
  2760. }
  2761. void WebContents::SelectAll() {
  2762. web_contents()->SelectAll();
  2763. }
  2764. void WebContents::Unselect() {
  2765. web_contents()->CollapseSelection();
  2766. }
  2767. void WebContents::ScrollToTopOfDocument() {
  2768. web_contents()->ScrollToTopOfDocument();
  2769. }
  2770. void WebContents::ScrollToBottomOfDocument() {
  2771. web_contents()->ScrollToBottomOfDocument();
  2772. }
  2773. void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
  2774. int start_adjust = 0;
  2775. int end_adjust = 0;
  2776. gin_helper::Dictionary dict;
  2777. if (args->GetNext(&dict)) {
  2778. dict.Get("start", &start_adjust);
  2779. dict.Get("matchCase", &end_adjust);
  2780. }
  2781. // The selection menu is a Chrome-specific piece of UI.
  2782. // TODO(codebytere): maybe surface as an event in the future?
  2783. web_contents()->AdjustSelectionByCharacterOffset(
  2784. start_adjust, end_adjust, false /* show_selection_menu */);
  2785. }
  2786. void WebContents::Replace(const std::u16string& word) {
  2787. web_contents()->Replace(word);
  2788. }
  2789. void WebContents::ReplaceMisspelling(const std::u16string& word) {
  2790. web_contents()->ReplaceMisspelling(word);
  2791. }
  2792. uint32_t WebContents::FindInPage(gin::Arguments* args) {
  2793. std::u16string search_text;
  2794. if (!args->GetNext(&search_text) || search_text.empty()) {
  2795. gin_helper::ErrorThrower(args->isolate())
  2796. .ThrowError("Must provide a non-empty search content");
  2797. return 0;
  2798. }
  2799. uint32_t request_id = ++find_in_page_request_id_;
  2800. gin_helper::Dictionary dict;
  2801. auto options = blink::mojom::FindOptions::New();
  2802. if (args->GetNext(&dict)) {
  2803. dict.Get("forward", &options->forward);
  2804. dict.Get("matchCase", &options->match_case);
  2805. dict.Get("findNext", &options->new_session);
  2806. }
  2807. web_contents()->Find(request_id, search_text, std::move(options));
  2808. return request_id;
  2809. }
  2810. void WebContents::StopFindInPage(content::StopFindAction action) {
  2811. web_contents()->StopFinding(action);
  2812. }
  2813. void WebContents::ShowDefinitionForSelection() {
  2814. #if BUILDFLAG(IS_MAC)
  2815. auto* const view = web_contents()->GetRenderWidgetHostView();
  2816. if (view)
  2817. view->ShowDefinitionForSelection();
  2818. #endif
  2819. }
  2820. void WebContents::CopyImageAt(int x, int y) {
  2821. auto* const host = web_contents()->GetPrimaryMainFrame();
  2822. if (host)
  2823. host->CopyImageAt(x, y);
  2824. }
  2825. void WebContents::Focus() {
  2826. // Focusing on WebContents does not automatically focus the window on macOS
  2827. // and Linux, do it manually to match the behavior on Windows.
  2828. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
  2829. if (owner_window())
  2830. owner_window()->Focus(true);
  2831. #endif
  2832. web_contents()->Focus();
  2833. }
  2834. #if !BUILDFLAG(IS_MAC)
  2835. bool WebContents::IsFocused() const {
  2836. auto* view = web_contents()->GetRenderWidgetHostView();
  2837. if (!view)
  2838. return false;
  2839. if (GetType() != Type::kBackgroundPage) {
  2840. auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
  2841. if (window && !window->IsVisible())
  2842. return false;
  2843. }
  2844. return view->HasFocus();
  2845. }
  2846. #endif
  2847. void WebContents::SendInputEvent(v8::Isolate* isolate,
  2848. v8::Local<v8::Value> input_event) {
  2849. content::RenderWidgetHostView* view =
  2850. web_contents()->GetRenderWidgetHostView();
  2851. if (!view)
  2852. return;
  2853. content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
  2854. blink::WebInputEvent::Type type =
  2855. gin::GetWebInputEventType(isolate, input_event);
  2856. if (blink::WebInputEvent::IsMouseEventType(type)) {
  2857. blink::WebMouseEvent mouse_event;
  2858. if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
  2859. if (IsOffScreen()) {
  2860. GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
  2861. } else {
  2862. rwh->ForwardMouseEvent(mouse_event);
  2863. }
  2864. return;
  2865. }
  2866. } else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
  2867. content::NativeWebKeyboardEvent keyboard_event(
  2868. blink::WebKeyboardEvent::Type::kRawKeyDown,
  2869. blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
  2870. if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
  2871. // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
  2872. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
  2873. keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
  2874. rwh->ForwardKeyboardEvent(keyboard_event);
  2875. return;
  2876. }
  2877. } else if (type == blink::WebInputEvent::Type::kMouseWheel) {
  2878. blink::WebMouseWheelEvent mouse_wheel_event;
  2879. if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
  2880. if (IsOffScreen()) {
  2881. GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
  2882. mouse_wheel_event);
  2883. } else {
  2884. // Chromium expects phase info in wheel events (and applies a
  2885. // DCHECK to verify it). See: https://crbug.com/756524.
  2886. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
  2887. mouse_wheel_event.dispatch_type =
  2888. blink::WebInputEvent::DispatchType::kBlocking;
  2889. rwh->ForwardWheelEvent(mouse_wheel_event);
  2890. // Send a synthetic wheel event with phaseEnded to finish scrolling.
  2891. mouse_wheel_event.has_synthetic_phase = true;
  2892. mouse_wheel_event.delta_x = 0;
  2893. mouse_wheel_event.delta_y = 0;
  2894. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
  2895. mouse_wheel_event.dispatch_type =
  2896. blink::WebInputEvent::DispatchType::kEventNonBlocking;
  2897. rwh->ForwardWheelEvent(mouse_wheel_event);
  2898. }
  2899. return;
  2900. }
  2901. }
  2902. isolate->ThrowException(
  2903. v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
  2904. }
  2905. void WebContents::BeginFrameSubscription(gin::Arguments* args) {
  2906. bool only_dirty = false;
  2907. FrameSubscriber::FrameCaptureCallback callback;
  2908. if (args->Length() > 1) {
  2909. if (!args->GetNext(&only_dirty)) {
  2910. args->ThrowError();
  2911. return;
  2912. }
  2913. }
  2914. if (!args->GetNext(&callback)) {
  2915. args->ThrowError();
  2916. return;
  2917. }
  2918. frame_subscriber_ =
  2919. std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
  2920. }
  2921. void WebContents::EndFrameSubscription() {
  2922. frame_subscriber_.reset();
  2923. }
  2924. void WebContents::StartDrag(const gin_helper::Dictionary& item,
  2925. gin::Arguments* args) {
  2926. base::FilePath file;
  2927. std::vector<base::FilePath> files;
  2928. if (!item.Get("files", &files) && item.Get("file", &file)) {
  2929. files.push_back(file);
  2930. }
  2931. v8::Local<v8::Value> icon_value;
  2932. if (!item.Get("icon", &icon_value)) {
  2933. gin_helper::ErrorThrower(args->isolate())
  2934. .ThrowError("'icon' parameter is required");
  2935. return;
  2936. }
  2937. NativeImage* icon = nullptr;
  2938. if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
  2939. icon->image().IsEmpty()) {
  2940. return;
  2941. }
  2942. // Start dragging.
  2943. if (!files.empty()) {
  2944. base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
  2945. DragFileItems(files, icon->image(), web_contents()->GetNativeView());
  2946. } else {
  2947. gin_helper::ErrorThrower(args->isolate())
  2948. .ThrowError("Must specify either 'file' or 'files' option");
  2949. }
  2950. }
  2951. v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
  2952. gin_helper::Promise<gfx::Image> promise(args->isolate());
  2953. v8::Local<v8::Promise> handle = promise.GetHandle();
  2954. gfx::Rect rect;
  2955. args->GetNext(&rect);
  2956. bool stay_hidden = false;
  2957. bool stay_awake = false;
  2958. if (args && args->Length() == 2) {
  2959. gin_helper::Dictionary options;
  2960. if (args->GetNext(&options)) {
  2961. options.Get("stayHidden", &stay_hidden);
  2962. options.Get("stayAwake", &stay_awake);
  2963. }
  2964. }
  2965. auto* const view = web_contents()->GetRenderWidgetHostView();
  2966. if (!view) {
  2967. promise.Resolve(gfx::Image());
  2968. return handle;
  2969. }
  2970. #if !BUILDFLAG(IS_MAC)
  2971. // If the view's renderer is suspended this may fail on Windows/Linux -
  2972. // bail if so. See CopyFromSurface in
  2973. // content/public/browser/render_widget_host_view.h.
  2974. auto* rfh = web_contents()->GetPrimaryMainFrame();
  2975. if (rfh &&
  2976. rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
  2977. promise.Resolve(gfx::Image());
  2978. return handle;
  2979. }
  2980. #endif // BUILDFLAG(IS_MAC)
  2981. auto capture_handle = web_contents()->IncrementCapturerCount(
  2982. rect.size(), stay_hidden, stay_awake);
  2983. // Capture full page if user doesn't specify a |rect|.
  2984. const gfx::Size view_size =
  2985. rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
  2986. // By default, the requested bitmap size is the view size in screen
  2987. // coordinates. However, if there's more pixel detail available on the
  2988. // current system, increase the requested bitmap size to capture it all.
  2989. gfx::Size bitmap_size = view_size;
  2990. const gfx::NativeView native_view = view->GetNativeView();
  2991. const float scale = display::Screen::GetScreen()
  2992. ->GetDisplayNearestView(native_view)
  2993. .device_scale_factor();
  2994. if (scale > 1.0f)
  2995. bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
  2996. view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
  2997. base::BindOnce(&OnCapturePageDone, std::move(promise),
  2998. std::move(capture_handle)));
  2999. return handle;
  3000. }
  3001. bool WebContents::IsBeingCaptured() {
  3002. return web_contents()->IsBeingCaptured();
  3003. }
  3004. void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
  3005. if (cursor.type() == ui::mojom::CursorType::kCustom) {
  3006. Emit("cursor-changed", CursorTypeToString(cursor.type()),
  3007. gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
  3008. cursor.image_scale_factor(),
  3009. gfx::Size(cursor.custom_bitmap().width(),
  3010. cursor.custom_bitmap().height()),
  3011. cursor.custom_hotspot());
  3012. } else {
  3013. Emit("cursor-changed", CursorTypeToString(cursor.type()));
  3014. }
  3015. }
  3016. bool WebContents::IsGuest() const {
  3017. return type_ == Type::kWebView;
  3018. }
  3019. void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
  3020. int embedder_frame_id) {
  3021. attached_ = true;
  3022. if (guest_delegate_)
  3023. guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
  3024. }
  3025. bool WebContents::IsOffScreen() const {
  3026. return type_ == Type::kOffScreen;
  3027. }
  3028. void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
  3029. Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
  3030. }
  3031. void WebContents::StartPainting() {
  3032. auto* osr_wcv = GetOffScreenWebContentsView();
  3033. if (osr_wcv)
  3034. osr_wcv->SetPainting(true);
  3035. }
  3036. void WebContents::StopPainting() {
  3037. auto* osr_wcv = GetOffScreenWebContentsView();
  3038. if (osr_wcv)
  3039. osr_wcv->SetPainting(false);
  3040. }
  3041. bool WebContents::IsPainting() const {
  3042. auto* osr_wcv = GetOffScreenWebContentsView();
  3043. return osr_wcv && osr_wcv->IsPainting();
  3044. }
  3045. void WebContents::SetFrameRate(int frame_rate) {
  3046. auto* osr_wcv = GetOffScreenWebContentsView();
  3047. if (osr_wcv)
  3048. osr_wcv->SetFrameRate(frame_rate);
  3049. }
  3050. int WebContents::GetFrameRate() const {
  3051. auto* osr_wcv = GetOffScreenWebContentsView();
  3052. return osr_wcv ? osr_wcv->GetFrameRate() : 0;
  3053. }
  3054. void WebContents::Invalidate() {
  3055. if (IsOffScreen()) {
  3056. auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
  3057. if (osr_rwhv)
  3058. osr_rwhv->Invalidate();
  3059. } else {
  3060. auto* const window = owner_window();
  3061. if (window)
  3062. window->Invalidate();
  3063. }
  3064. }
  3065. gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
  3066. if (IsOffScreen() && wc == web_contents()) {
  3067. auto* relay = NativeWindowRelay::FromWebContents(web_contents());
  3068. if (relay) {
  3069. auto* owner_window = relay->GetNativeWindow();
  3070. return owner_window ? owner_window->GetSize() : gfx::Size();
  3071. }
  3072. }
  3073. return gfx::Size();
  3074. }
  3075. void WebContents::SetZoomLevel(double level) {
  3076. zoom_controller_->SetZoomLevel(level);
  3077. }
  3078. double WebContents::GetZoomLevel() const {
  3079. return zoom_controller_->GetZoomLevel();
  3080. }
  3081. void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
  3082. double factor) {
  3083. if (factor < std::numeric_limits<double>::epsilon()) {
  3084. thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
  3085. return;
  3086. }
  3087. auto level = blink::PageZoomFactorToZoomLevel(factor);
  3088. SetZoomLevel(level);
  3089. }
  3090. double WebContents::GetZoomFactor() const {
  3091. auto level = GetZoomLevel();
  3092. return blink::PageZoomLevelToZoomFactor(level);
  3093. }
  3094. void WebContents::SetTemporaryZoomLevel(double level) {
  3095. zoom_controller_->SetTemporaryZoomLevel(level);
  3096. }
  3097. void WebContents::DoGetZoomLevel(
  3098. electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
  3099. callback) {
  3100. std::move(callback).Run(GetZoomLevel());
  3101. }
  3102. std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
  3103. auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
  3104. if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
  3105. base::FilePath preload;
  3106. if (web_preferences->GetPreloadPath(&preload)) {
  3107. result.emplace_back(preload);
  3108. }
  3109. }
  3110. return result;
  3111. }
  3112. v8::Local<v8::Value> WebContents::GetLastWebPreferences(
  3113. v8::Isolate* isolate) const {
  3114. auto* web_preferences = WebContentsPreferences::From(web_contents());
  3115. if (!web_preferences)
  3116. return v8::Null(isolate);
  3117. return gin::ConvertToV8(isolate, *web_preferences->last_preference());
  3118. }
  3119. v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
  3120. v8::Isolate* isolate) const {
  3121. if (owner_window())
  3122. return BrowserWindow::From(isolate, owner_window());
  3123. else
  3124. return v8::Null(isolate);
  3125. }
  3126. v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
  3127. return v8::Local<v8::Value>::New(isolate, session_);
  3128. }
  3129. content::WebContents* WebContents::HostWebContents() const {
  3130. if (!embedder_)
  3131. return nullptr;
  3132. return embedder_->web_contents();
  3133. }
  3134. void WebContents::SetEmbedder(const WebContents* embedder) {
  3135. if (embedder) {
  3136. NativeWindow* owner_window = nullptr;
  3137. auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
  3138. if (relay) {
  3139. owner_window = relay->GetNativeWindow();
  3140. }
  3141. if (owner_window)
  3142. SetOwnerWindow(owner_window);
  3143. content::RenderWidgetHostView* rwhv =
  3144. web_contents()->GetRenderWidgetHostView();
  3145. if (rwhv) {
  3146. rwhv->Hide();
  3147. rwhv->Show();
  3148. }
  3149. }
  3150. }
  3151. void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
  3152. if (inspectable_web_contents_)
  3153. inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
  3154. }
  3155. v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
  3156. gfx::NativeView ptr = web_contents()->GetNativeView();
  3157. auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
  3158. sizeof(gfx::NativeView));
  3159. if (buffer.IsEmpty())
  3160. return v8::Null(isolate);
  3161. else
  3162. return buffer.ToLocalChecked();
  3163. }
  3164. v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
  3165. if (devtools_web_contents_.IsEmpty())
  3166. return v8::Null(isolate);
  3167. else
  3168. return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
  3169. }
  3170. v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
  3171. if (debugger_.IsEmpty()) {
  3172. auto handle = electron::api::Debugger::Create(isolate, web_contents());
  3173. debugger_.Reset(isolate, handle.ToV8());
  3174. }
  3175. return v8::Local<v8::Value>::New(isolate, debugger_);
  3176. }
  3177. content::RenderFrameHost* WebContents::MainFrame() {
  3178. return web_contents()->GetPrimaryMainFrame();
  3179. }
  3180. content::RenderFrameHost* WebContents::Opener() {
  3181. return web_contents()->GetOpener();
  3182. }
  3183. void WebContents::NotifyUserActivation() {
  3184. content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
  3185. if (frame)
  3186. frame->NotifyUserActivation(
  3187. blink::mojom::UserActivationNotificationType::kInteraction);
  3188. }
  3189. void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
  3190. auto* web_preferences = WebContentsPreferences::From(web_contents());
  3191. web_preferences->SetImageAnimationPolicy(new_policy);
  3192. web_contents()->OnWebPreferencesChanged();
  3193. }
  3194. void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
  3195. Emit("input-event", event);
  3196. }
  3197. v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
  3198. gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
  3199. v8::Local<v8::Promise> handle = promise.GetHandle();
  3200. auto* frame_host = web_contents()->GetPrimaryMainFrame();
  3201. if (!frame_host) {
  3202. promise.RejectWithErrorMessage("Failed to create memory dump");
  3203. return handle;
  3204. }
  3205. auto pid = frame_host->GetProcess()->GetProcess().Pid();
  3206. v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
  3207. memory_instrumentation::MemoryInstrumentation::GetInstance()
  3208. ->RequestGlobalDumpForPid(
  3209. pid, std::vector<std::string>(),
  3210. base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
  3211. std::move(context), std::move(promise), pid));
  3212. return handle;
  3213. }
  3214. v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
  3215. v8::Isolate* isolate,
  3216. const base::FilePath& file_path) {
  3217. gin_helper::Promise<void> promise(isolate);
  3218. v8::Local<v8::Promise> handle = promise.GetHandle();
  3219. ScopedAllowBlockingForElectron allow_blocking;
  3220. uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
  3221. // The snapshot file is passed to an untrusted process.
  3222. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
  3223. base::File file(file_path, flags);
  3224. if (!file.IsValid()) {
  3225. promise.RejectWithErrorMessage(
  3226. "Failed to take heap snapshot with invalid file path " +
  3227. #if BUILDFLAG(IS_WIN)
  3228. base::WideToUTF8(file_path.value()));
  3229. #else
  3230. file_path.value());
  3231. #endif
  3232. return handle;
  3233. }
  3234. auto* frame_host = web_contents()->GetPrimaryMainFrame();
  3235. if (!frame_host) {
  3236. promise.RejectWithErrorMessage(
  3237. "Failed to take heap snapshot with invalid webContents main frame");
  3238. return handle;
  3239. }
  3240. if (!frame_host->IsRenderFrameLive()) {
  3241. promise.RejectWithErrorMessage(
  3242. "Failed to take heap snapshot with nonexistent render frame");
  3243. return handle;
  3244. }
  3245. // This dance with `base::Owned` is to ensure that the interface stays alive
  3246. // until the callback is called. Otherwise it would be closed at the end of
  3247. // this function.
  3248. auto electron_renderer =
  3249. std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
  3250. frame_host->GetRemoteInterfaces()->GetInterface(
  3251. electron_renderer->BindNewPipeAndPassReceiver());
  3252. auto* raw_ptr = electron_renderer.get();
  3253. (*raw_ptr)->TakeHeapSnapshot(
  3254. mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
  3255. base::BindOnce(
  3256. [](mojo::Remote<mojom::ElectronRenderer>* ep,
  3257. gin_helper::Promise<void> promise, bool success) {
  3258. if (success) {
  3259. promise.Resolve();
  3260. } else {
  3261. promise.RejectWithErrorMessage("Failed to take heap snapshot");
  3262. }
  3263. },
  3264. base::Owned(std::move(electron_renderer)), std::move(promise)));
  3265. return handle;
  3266. }
  3267. void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
  3268. const gfx::Size& pref_size) {
  3269. Emit("preferred-size-changed", pref_size);
  3270. }
  3271. bool WebContents::CanOverscrollContent() {
  3272. return false;
  3273. }
  3274. std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
  3275. content::RenderFrameHost* frame,
  3276. content::EyeDropperListener* listener) {
  3277. return ShowEyeDropper(frame, listener);
  3278. }
  3279. void WebContents::RunFileChooser(
  3280. content::RenderFrameHost* render_frame_host,
  3281. scoped_refptr<content::FileSelectListener> listener,
  3282. const blink::mojom::FileChooserParams& params) {
  3283. FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
  3284. params);
  3285. }
  3286. void WebContents::EnumerateDirectory(
  3287. content::WebContents* web_contents,
  3288. scoped_refptr<content::FileSelectListener> listener,
  3289. const base::FilePath& path) {
  3290. FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
  3291. }
  3292. bool WebContents::IsFullscreenForTabOrPending(
  3293. const content::WebContents* source) {
  3294. if (!owner_window())
  3295. return is_html_fullscreen();
  3296. bool in_transition = owner_window()->fullscreen_transition_state() !=
  3297. NativeWindow::FullScreenTransitionState::kNone;
  3298. bool is_html_transition = owner_window()->fullscreen_transition_type() ==
  3299. NativeWindow::FullScreenTransitionType::kHTML;
  3300. return is_html_fullscreen() || (in_transition && is_html_transition);
  3301. }
  3302. content::FullscreenState WebContents::GetFullscreenState(
  3303. const content::WebContents* source) const {
  3304. // `const_cast` here because EAM does not have const getters
  3305. return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
  3306. ->fullscreen_controller()
  3307. ->GetFullscreenState(source);
  3308. }
  3309. bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
  3310. if (source && source->GetOutermostWebContents() == source) {
  3311. // If this is the outermost web contents and the user has tabbed or
  3312. // shift + tabbed through all the elements, reset the focus back to
  3313. // the first or last element so that it doesn't stay in the body.
  3314. source->FocusThroughTabTraversal(reverse);
  3315. return true;
  3316. }
  3317. return false;
  3318. }
  3319. content::PictureInPictureResult WebContents::EnterPictureInPicture(
  3320. content::WebContents* web_contents) {
  3321. return PictureInPictureWindowManager::GetInstance()
  3322. ->EnterVideoPictureInPicture(web_contents);
  3323. }
  3324. void WebContents::ExitPictureInPicture() {
  3325. PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
  3326. }
  3327. void WebContents::DevToolsSaveToFile(const std::string& url,
  3328. const std::string& content,
  3329. bool save_as) {
  3330. base::FilePath path;
  3331. auto it = saved_files_.find(url);
  3332. if (it != saved_files_.end() && !save_as) {
  3333. path = it->second;
  3334. } else {
  3335. file_dialog::DialogSettings settings;
  3336. settings.parent_window = owner_window();
  3337. settings.force_detached = offscreen_;
  3338. settings.title = url;
  3339. settings.default_path = base::FilePath::FromUTF8Unsafe(url);
  3340. if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
  3341. inspectable_web_contents_->CallClientFunction(
  3342. "DevToolsAPI", "canceledSaveURL", base::Value(url));
  3343. return;
  3344. }
  3345. }
  3346. saved_files_[url] = path;
  3347. // Notify DevTools.
  3348. inspectable_web_contents_->CallClientFunction(
  3349. "DevToolsAPI", "savedURL", base::Value(url),
  3350. base::Value(path.AsUTF8Unsafe()));
  3351. file_task_runner_->PostTask(FROM_HERE,
  3352. base::BindOnce(&WriteToFile, path, content));
  3353. }
  3354. void WebContents::DevToolsAppendToFile(const std::string& url,
  3355. const std::string& content) {
  3356. auto it = saved_files_.find(url);
  3357. if (it == saved_files_.end())
  3358. return;
  3359. // Notify DevTools.
  3360. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
  3361. base::Value(url));
  3362. file_task_runner_->PostTask(
  3363. FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
  3364. }
  3365. void WebContents::DevToolsRequestFileSystems() {
  3366. auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
  3367. if (file_system_paths.empty()) {
  3368. inspectable_web_contents_->CallClientFunction(
  3369. "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
  3370. return;
  3371. }
  3372. std::vector<FileSystem> file_systems;
  3373. for (const auto& file_system_path : file_system_paths) {
  3374. base::FilePath path =
  3375. base::FilePath::FromUTF8Unsafe(file_system_path.first);
  3376. std::string file_system_id =
  3377. RegisterFileSystem(GetDevToolsWebContents(), path);
  3378. FileSystem file_system =
  3379. CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
  3380. file_system_path.first, file_system_path.second);
  3381. file_systems.push_back(file_system);
  3382. }
  3383. base::Value::List file_system_value;
  3384. for (const auto& file_system : file_systems)
  3385. file_system_value.Append(CreateFileSystemValue(file_system));
  3386. inspectable_web_contents_->CallClientFunction(
  3387. "DevToolsAPI", "fileSystemsLoaded",
  3388. base::Value(std::move(file_system_value)));
  3389. }
  3390. void WebContents::DevToolsAddFileSystem(
  3391. const std::string& type,
  3392. const base::FilePath& file_system_path) {
  3393. base::FilePath path = file_system_path;
  3394. if (path.empty()) {
  3395. std::vector<base::FilePath> paths;
  3396. file_dialog::DialogSettings settings;
  3397. settings.parent_window = owner_window();
  3398. settings.force_detached = offscreen_;
  3399. settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
  3400. if (!file_dialog::ShowOpenDialogSync(settings, &paths))
  3401. return;
  3402. path = paths[0];
  3403. }
  3404. std::string file_system_id =
  3405. RegisterFileSystem(GetDevToolsWebContents(), path);
  3406. if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
  3407. return;
  3408. FileSystem file_system = CreateFileSystemStruct(
  3409. GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
  3410. base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
  3411. auto* pref_service = GetPrefService(GetDevToolsWebContents());
  3412. ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
  3413. update->Set(path.AsUTF8Unsafe(), type);
  3414. std::string error = ""; // No error
  3415. inspectable_web_contents_->CallClientFunction(
  3416. "DevToolsAPI", "fileSystemAdded", base::Value(error),
  3417. base::Value(std::move(file_system_value)));
  3418. }
  3419. void WebContents::DevToolsRemoveFileSystem(
  3420. const base::FilePath& file_system_path) {
  3421. if (!inspectable_web_contents_)
  3422. return;
  3423. std::string path = file_system_path.AsUTF8Unsafe();
  3424. storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
  3425. file_system_path);
  3426. auto* pref_service = GetPrefService(GetDevToolsWebContents());
  3427. ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
  3428. update->Remove(path);
  3429. inspectable_web_contents_->CallClientFunction(
  3430. "DevToolsAPI", "fileSystemRemoved", base::Value(path));
  3431. }
  3432. void WebContents::DevToolsIndexPath(
  3433. int request_id,
  3434. const std::string& file_system_path,
  3435. const std::string& excluded_folders_message) {
  3436. if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
  3437. OnDevToolsIndexingDone(request_id, file_system_path);
  3438. return;
  3439. }
  3440. if (devtools_indexing_jobs_.count(request_id) != 0)
  3441. return;
  3442. std::vector<std::string> excluded_folders;
  3443. absl::optional<base::Value> parsed_excluded_folders =
  3444. base::JSONReader::Read(excluded_folders_message);
  3445. if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
  3446. for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
  3447. if (folder_path.is_string())
  3448. excluded_folders.push_back(folder_path.GetString());
  3449. }
  3450. }
  3451. devtools_indexing_jobs_[request_id] =
  3452. scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
  3453. devtools_file_system_indexer_->IndexPath(
  3454. file_system_path, excluded_folders,
  3455. base::BindRepeating(
  3456. &WebContents::OnDevToolsIndexingWorkCalculated,
  3457. weak_factory_.GetWeakPtr(), request_id, file_system_path),
  3458. base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
  3459. weak_factory_.GetWeakPtr(), request_id,
  3460. file_system_path),
  3461. base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
  3462. weak_factory_.GetWeakPtr(), request_id,
  3463. file_system_path)));
  3464. }
  3465. void WebContents::DevToolsStopIndexing(int request_id) {
  3466. auto it = devtools_indexing_jobs_.find(request_id);
  3467. if (it == devtools_indexing_jobs_.end())
  3468. return;
  3469. it->second->Stop();
  3470. devtools_indexing_jobs_.erase(it);
  3471. }
  3472. void WebContents::DevToolsOpenInNewTab(const std::string& url) {
  3473. Emit("devtools-open-url", url);
  3474. }
  3475. void WebContents::DevToolsSearchInPath(int request_id,
  3476. const std::string& file_system_path,
  3477. const std::string& query) {
  3478. if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
  3479. OnDevToolsSearchCompleted(request_id, file_system_path,
  3480. std::vector<std::string>());
  3481. return;
  3482. }
  3483. devtools_file_system_indexer_->SearchInPath(
  3484. file_system_path, query,
  3485. base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
  3486. weak_factory_.GetWeakPtr(), request_id,
  3487. file_system_path));
  3488. }
  3489. void WebContents::DevToolsSetEyeDropperActive(bool active) {
  3490. auto* web_contents = GetWebContents();
  3491. if (!web_contents)
  3492. return;
  3493. if (active) {
  3494. eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
  3495. web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
  3496. base::Unretained(this)));
  3497. } else {
  3498. eye_dropper_.reset();
  3499. }
  3500. }
  3501. void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
  3502. base::Value::Dict color;
  3503. color.Set("r", r);
  3504. color.Set("g", g);
  3505. color.Set("b", b);
  3506. color.Set("a", a);
  3507. inspectable_web_contents_->CallClientFunction(
  3508. "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
  3509. }
  3510. #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
  3511. ui::ImageModel WebContents::GetDevToolsWindowIcon() {
  3512. return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
  3513. }
  3514. #endif
  3515. #if BUILDFLAG(IS_LINUX)
  3516. void WebContents::GetDevToolsWindowWMClass(std::string* name,
  3517. std::string* class_name) {
  3518. *class_name = Browser::Get()->GetName();
  3519. *name = base::ToLowerASCII(*class_name);
  3520. }
  3521. #endif
  3522. void WebContents::OnDevToolsIndexingWorkCalculated(
  3523. int request_id,
  3524. const std::string& file_system_path,
  3525. int total_work) {
  3526. inspectable_web_contents_->CallClientFunction(
  3527. "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
  3528. base::Value(file_system_path), base::Value(total_work));
  3529. }
  3530. void WebContents::OnDevToolsIndexingWorked(int request_id,
  3531. const std::string& file_system_path,
  3532. int worked) {
  3533. inspectable_web_contents_->CallClientFunction(
  3534. "DevToolsAPI", "indexingWorked", base::Value(request_id),
  3535. base::Value(file_system_path), base::Value(worked));
  3536. }
  3537. void WebContents::OnDevToolsIndexingDone(int request_id,
  3538. const std::string& file_system_path) {
  3539. devtools_indexing_jobs_.erase(request_id);
  3540. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
  3541. base::Value(request_id),
  3542. base::Value(file_system_path));
  3543. }
  3544. void WebContents::OnDevToolsSearchCompleted(
  3545. int request_id,
  3546. const std::string& file_system_path,
  3547. const std::vector<std::string>& file_paths) {
  3548. base::Value::List file_paths_value;
  3549. for (const auto& file_path : file_paths)
  3550. file_paths_value.Append(file_path);
  3551. inspectable_web_contents_->CallClientFunction(
  3552. "DevToolsAPI", "searchCompleted", base::Value(request_id),
  3553. base::Value(file_system_path), base::Value(std::move(file_paths_value)));
  3554. }
  3555. void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
  3556. // Window is already in fullscreen mode, save the state.
  3557. if (enter_fullscreen && owner_window()->IsFullscreen()) {
  3558. native_fullscreen_ = true;
  3559. UpdateHtmlApiFullscreen(true);
  3560. return;
  3561. }
  3562. // Exit html fullscreen state but not window's fullscreen mode.
  3563. if (!enter_fullscreen && native_fullscreen_) {
  3564. UpdateHtmlApiFullscreen(false);
  3565. return;
  3566. }
  3567. // Set fullscreen on window if allowed.
  3568. auto* web_preferences = WebContentsPreferences::From(GetWebContents());
  3569. bool html_fullscreenable =
  3570. web_preferences
  3571. ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
  3572. : true;
  3573. if (html_fullscreenable)
  3574. owner_window_->SetFullScreen(enter_fullscreen);
  3575. UpdateHtmlApiFullscreen(enter_fullscreen);
  3576. native_fullscreen_ = false;
  3577. }
  3578. void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
  3579. if (fullscreen == is_html_fullscreen())
  3580. return;
  3581. html_fullscreen_ = fullscreen;
  3582. // Notify renderer of the html fullscreen change.
  3583. web_contents()
  3584. ->GetRenderViewHost()
  3585. ->GetWidget()
  3586. ->SynchronizeVisualProperties();
  3587. // The embedder WebContents is separated from the frame tree of webview, so
  3588. // we must manually sync their fullscreen states.
  3589. if (embedder_)
  3590. embedder_->SetHtmlApiFullscreen(fullscreen);
  3591. if (fullscreen) {
  3592. Emit("enter-html-full-screen");
  3593. owner_window_->NotifyWindowEnterHtmlFullScreen();
  3594. } else {
  3595. Emit("leave-html-full-screen");
  3596. owner_window_->NotifyWindowLeaveHtmlFullScreen();
  3597. }
  3598. // Make sure all child webviews quit html fullscreen.
  3599. if (!fullscreen && !IsGuest()) {
  3600. auto* manager = WebViewManager::GetWebViewManager(web_contents());
  3601. manager->ForEachGuest(
  3602. web_contents(), base::BindRepeating([](content::WebContents* guest) {
  3603. WebContents* api_web_contents = WebContents::From(guest);
  3604. api_web_contents->SetHtmlApiFullscreen(false);
  3605. return false;
  3606. }));
  3607. }
  3608. }
  3609. // static
  3610. void WebContents::FillObjectTemplate(v8::Isolate* isolate,
  3611. v8::Local<v8::ObjectTemplate> templ) {
  3612. gin::InvokerOptions options;
  3613. options.holder_is_first_argument = true;
  3614. options.holder_type = GetClassName();
  3615. templ->Set(
  3616. gin::StringToSymbol(isolate, "isDestroyed"),
  3617. gin::CreateFunctionTemplate(
  3618. isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
  3619. options));
  3620. // We use gin_helper::ObjectTemplateBuilder instead of
  3621. // gin::ObjectTemplateBuilder here to handle the fact that WebContents is
  3622. // destroyable.
  3623. gin_helper::ObjectTemplateBuilder(isolate, templ)
  3624. .SetMethod("destroy", &WebContents::Destroy)
  3625. .SetMethod("close", &WebContents::Close)
  3626. .SetMethod("getBackgroundThrottling",
  3627. &WebContents::GetBackgroundThrottling)
  3628. .SetMethod("setBackgroundThrottling",
  3629. &WebContents::SetBackgroundThrottling)
  3630. .SetMethod("getProcessId", &WebContents::GetProcessID)
  3631. .SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
  3632. .SetMethod("equal", &WebContents::Equal)
  3633. .SetMethod("_loadURL", &WebContents::LoadURL)
  3634. .SetMethod("reload", &WebContents::Reload)
  3635. .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
  3636. .SetMethod("downloadURL", &WebContents::DownloadURL)
  3637. .SetMethod("getURL", &WebContents::GetURL)
  3638. .SetMethod("getTitle", &WebContents::GetTitle)
  3639. .SetMethod("isLoading", &WebContents::IsLoading)
  3640. .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
  3641. .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
  3642. .SetMethod("stop", &WebContents::Stop)
  3643. .SetMethod("canGoBack", &WebContents::CanGoBack)
  3644. .SetMethod("goBack", &WebContents::GoBack)
  3645. .SetMethod("canGoForward", &WebContents::CanGoForward)
  3646. .SetMethod("goForward", &WebContents::GoForward)
  3647. .SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
  3648. .SetMethod("goToOffset", &WebContents::GoToOffset)
  3649. .SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
  3650. .SetMethod("goToIndex", &WebContents::GoToIndex)
  3651. .SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
  3652. .SetMethod("clearHistory", &WebContents::ClearHistory)
  3653. .SetMethod("length", &WebContents::GetHistoryLength)
  3654. .SetMethod("isCrashed", &WebContents::IsCrashed)
  3655. .SetMethod("forcefullyCrashRenderer",
  3656. &WebContents::ForcefullyCrashRenderer)
  3657. .SetMethod("setUserAgent", &WebContents::SetUserAgent)
  3658. .SetMethod("getUserAgent", &WebContents::GetUserAgent)
  3659. .SetMethod("savePage", &WebContents::SavePage)
  3660. .SetMethod("openDevTools", &WebContents::OpenDevTools)
  3661. .SetMethod("closeDevTools", &WebContents::CloseDevTools)
  3662. .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
  3663. .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
  3664. .SetMethod("getDevToolsTitle", &WebContents::GetDevToolsTitle)
  3665. .SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle)
  3666. .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
  3667. .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
  3668. .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
  3669. .SetMethod("inspectElement", &WebContents::InspectElement)
  3670. .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
  3671. .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
  3672. .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
  3673. .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
  3674. .SetMethod("undo", &WebContents::Undo)
  3675. .SetMethod("redo", &WebContents::Redo)
  3676. .SetMethod("cut", &WebContents::Cut)
  3677. .SetMethod("copy", &WebContents::Copy)
  3678. .SetMethod("centerSelection", &WebContents::CenterSelection)
  3679. .SetMethod("paste", &WebContents::Paste)
  3680. .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
  3681. .SetMethod("delete", &WebContents::Delete)
  3682. .SetMethod("selectAll", &WebContents::SelectAll)
  3683. .SetMethod("unselect", &WebContents::Unselect)
  3684. .SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
  3685. .SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
  3686. .SetMethod("adjustSelection",
  3687. &WebContents::AdjustSelectionByCharacterOffset)
  3688. .SetMethod("replace", &WebContents::Replace)
  3689. .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
  3690. .SetMethod("findInPage", &WebContents::FindInPage)
  3691. .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
  3692. .SetMethod("focus", &WebContents::Focus)
  3693. .SetMethod("isFocused", &WebContents::IsFocused)
  3694. .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
  3695. .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
  3696. .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
  3697. .SetMethod("startDrag", &WebContents::StartDrag)
  3698. .SetMethod("attachToIframe", &WebContents::AttachToIframe)
  3699. .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
  3700. .SetMethod("isOffscreen", &WebContents::IsOffScreen)
  3701. .SetMethod("startPainting", &WebContents::StartPainting)
  3702. .SetMethod("stopPainting", &WebContents::StopPainting)
  3703. .SetMethod("isPainting", &WebContents::IsPainting)
  3704. .SetMethod("setFrameRate", &WebContents::SetFrameRate)
  3705. .SetMethod("getFrameRate", &WebContents::GetFrameRate)
  3706. .SetMethod("invalidate", &WebContents::Invalidate)
  3707. .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
  3708. .SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
  3709. .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
  3710. .SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
  3711. .SetMethod("getType", &WebContents::GetType)
  3712. .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
  3713. .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
  3714. .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
  3715. .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
  3716. .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
  3717. .SetMethod("inspectSharedWorkerById",
  3718. &WebContents::InspectSharedWorkerById)
  3719. .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
  3720. #if BUILDFLAG(ENABLE_PRINTING)
  3721. .SetMethod("_print", &WebContents::Print)
  3722. .SetMethod("_printToPDF", &WebContents::PrintToPDF)
  3723. #endif
  3724. .SetMethod("_setNextChildWebPreferences",
  3725. &WebContents::SetNextChildWebPreferences)
  3726. .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
  3727. .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
  3728. .SetMethod("showDefinitionForSelection",
  3729. &WebContents::ShowDefinitionForSelection)
  3730. .SetMethod("copyImageAt", &WebContents::CopyImageAt)
  3731. .SetMethod("capturePage", &WebContents::CapturePage)
  3732. .SetMethod("setEmbedder", &WebContents::SetEmbedder)
  3733. .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
  3734. .SetMethod("getNativeView", &WebContents::GetNativeView)
  3735. .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
  3736. .SetMethod("setWebRTCIPHandlingPolicy",
  3737. &WebContents::SetWebRTCIPHandlingPolicy)
  3738. .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
  3739. .SetMethod("getWebRTCIPHandlingPolicy",
  3740. &WebContents::GetWebRTCIPHandlingPolicy)
  3741. .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
  3742. .SetMethod("setImageAnimationPolicy",
  3743. &WebContents::SetImageAnimationPolicy)
  3744. .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
  3745. .SetProperty("id", &WebContents::ID)
  3746. .SetProperty("session", &WebContents::Session)
  3747. .SetProperty("hostWebContents", &WebContents::HostWebContents)
  3748. .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
  3749. .SetProperty("debugger", &WebContents::Debugger)
  3750. .SetProperty("mainFrame", &WebContents::MainFrame)
  3751. .SetProperty("opener", &WebContents::Opener)
  3752. .Build();
  3753. }
  3754. const char* WebContents::GetTypeName() {
  3755. return GetClassName();
  3756. }
  3757. ElectronBrowserContext* WebContents::GetBrowserContext() const {
  3758. return static_cast<ElectronBrowserContext*>(
  3759. web_contents()->GetBrowserContext());
  3760. }
  3761. // static
  3762. gin::Handle<WebContents> WebContents::New(
  3763. v8::Isolate* isolate,
  3764. const gin_helper::Dictionary& options) {
  3765. gin::Handle<WebContents> handle =
  3766. gin::CreateHandle(isolate, new WebContents(isolate, options));
  3767. v8::TryCatch try_catch(isolate);
  3768. gin_helper::CallMethod(isolate, handle.get(), "_init");
  3769. if (try_catch.HasCaught()) {
  3770. node::errors::TriggerUncaughtException(isolate, try_catch);
  3771. }
  3772. return handle;
  3773. }
  3774. // static
  3775. gin::Handle<WebContents> WebContents::CreateAndTake(
  3776. v8::Isolate* isolate,
  3777. std::unique_ptr<content::WebContents> web_contents,
  3778. Type type) {
  3779. gin::Handle<WebContents> handle = gin::CreateHandle(
  3780. isolate, new WebContents(isolate, std::move(web_contents), type));
  3781. v8::TryCatch try_catch(isolate);
  3782. gin_helper::CallMethod(isolate, handle.get(), "_init");
  3783. if (try_catch.HasCaught()) {
  3784. node::errors::TriggerUncaughtException(isolate, try_catch);
  3785. }
  3786. return handle;
  3787. }
  3788. // static
  3789. WebContents* WebContents::From(content::WebContents* web_contents) {
  3790. if (!web_contents)
  3791. return nullptr;
  3792. auto* data = static_cast<UserDataLink*>(
  3793. web_contents->GetUserData(kElectronApiWebContentsKey));
  3794. return data ? data->web_contents.get() : nullptr;
  3795. }
  3796. // static
  3797. gin::Handle<WebContents> WebContents::FromOrCreate(
  3798. v8::Isolate* isolate,
  3799. content::WebContents* web_contents) {
  3800. WebContents* api_web_contents = From(web_contents);
  3801. if (!api_web_contents) {
  3802. api_web_contents = new WebContents(isolate, web_contents);
  3803. v8::TryCatch try_catch(isolate);
  3804. gin_helper::CallMethod(isolate, api_web_contents, "_init");
  3805. if (try_catch.HasCaught()) {
  3806. node::errors::TriggerUncaughtException(isolate, try_catch);
  3807. }
  3808. }
  3809. return gin::CreateHandle(isolate, api_web_contents);
  3810. }
  3811. // static
  3812. gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
  3813. v8::Isolate* isolate,
  3814. const gin_helper::Dictionary& web_preferences) {
  3815. // Check if webPreferences has |webContents| option.
  3816. gin::Handle<WebContents> web_contents;
  3817. if (web_preferences.GetHidden("webContents", &web_contents) &&
  3818. !web_contents.IsEmpty()) {
  3819. // Set webPreferences from options if using an existing webContents.
  3820. // These preferences will be used when the webContent launches new
  3821. // render processes.
  3822. auto* existing_preferences =
  3823. WebContentsPreferences::From(web_contents->web_contents());
  3824. gin_helper::Dictionary web_preferences_dict;
  3825. if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
  3826. &web_preferences_dict)) {
  3827. existing_preferences->SetFromDictionary(web_preferences_dict);
  3828. absl::optional<SkColor> color =
  3829. existing_preferences->GetBackgroundColor();
  3830. web_contents->web_contents()->SetPageBaseBackgroundColor(color);
  3831. // Because web preferences don't recognize transparency,
  3832. // only set rwhv background color if a color exists
  3833. auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
  3834. if (rwhv && color.has_value())
  3835. SetBackgroundColor(rwhv, color.value());
  3836. }
  3837. } else {
  3838. // Create one if not.
  3839. web_contents = WebContents::New(isolate, web_preferences);
  3840. }
  3841. return web_contents;
  3842. }
  3843. // static
  3844. WebContents* WebContents::FromID(int32_t id) {
  3845. return GetAllWebContents().Lookup(id);
  3846. }
  3847. // static
  3848. std::list<WebContents*> WebContents::GetWebContentsList() {
  3849. std::list<WebContents*> list;
  3850. for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
  3851. !iter.IsAtEnd(); iter.Advance()) {
  3852. list.push_back(iter.GetCurrentValue());
  3853. }
  3854. return list;
  3855. }
  3856. // static
  3857. gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
  3858. } // namespace electron::api
  3859. namespace {
  3860. using electron::api::GetAllWebContents;
  3861. using electron::api::WebContents;
  3862. using electron::api::WebFrameMain;
  3863. gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
  3864. WebContents* contents = WebContents::FromID(id);
  3865. return contents ? gin::CreateHandle(isolate, contents)
  3866. : gin::Handle<WebContents>();
  3867. }
  3868. gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
  3869. WebFrameMain* web_frame) {
  3870. content::RenderFrameHost* rfh = web_frame->render_frame_host();
  3871. content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
  3872. WebContents* contents = WebContents::From(source);
  3873. return contents ? gin::CreateHandle(isolate, contents)
  3874. : gin::Handle<WebContents>();
  3875. }
  3876. gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
  3877. v8::Isolate* isolate,
  3878. std::string target_id) {
  3879. auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
  3880. WebContents* contents =
  3881. agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
  3882. return contents ? gin::CreateHandle(isolate, contents)
  3883. : gin::Handle<WebContents>();
  3884. }
  3885. std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
  3886. v8::Isolate* isolate) {
  3887. std::vector<gin::Handle<WebContents>> list;
  3888. for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
  3889. !iter.IsAtEnd(); iter.Advance()) {
  3890. list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
  3891. }
  3892. return list;
  3893. }
  3894. void Initialize(v8::Local<v8::Object> exports,
  3895. v8::Local<v8::Value> unused,
  3896. v8::Local<v8::Context> context,
  3897. void* priv) {
  3898. v8::Isolate* isolate = context->GetIsolate();
  3899. gin_helper::Dictionary dict(isolate, exports);
  3900. dict.Set("WebContents", WebContents::GetConstructor(context));
  3901. dict.SetMethod("fromId", &WebContentsFromID);
  3902. dict.SetMethod("fromFrame", &WebContentsFromFrame);
  3903. dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
  3904. dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
  3905. }
  3906. } // namespace
  3907. NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)