electron_api_web_contents.cc 162 KB

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