electron_api_web_contents.cc 164 KB

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