/**
 Extensions that read or write to web pages utilize a content script. The content script
 contains JavaScript that executes in the contexts of a page that has been loaded into
 the browser. Content scripts read and modify the DOM of web pages the browser visits.
 https://developer.chrome.com/docs/extensions/mv3/architecture-overview/#contentScripts
 */ import { CONTENT_SCRIPT_PORT , ExternalMethods , MessageFromContentScript , MessageToContentScript , MESSAGE_SOURCE , } from '@shared/message-types' ; import { AuthenticationRequestEvent , DomEventName , TransactionRequestEvent , } from '@shared/inpage-types' ; import { RouteUrls } from '@shared/route-urls' ; import { getEventSourceWindow } from '@shared/utils/get-event-source-window' ; window . addEventListener ( 'message' , event => { const { data } = event ; if ( data . source === 'blockstack-app' ) { const { method } = data ; if ( method === 'getURL' ) { const url = chrome . runtime . getURL ( 'index.html' ) ; const source = getEventSourceWindow ( event ) ; source ?. postMessage ( { url , method : 'getURLResponse' , source : 'blockstack-extension' , } , event . origin ) ; return ; } } } ) ; const backgroundPort = chrome . runtime . connect ( { name : CONTENT_SCRIPT_PORT } ) ; function sendMessageToBackground ( message ) { backgroundPort . postMessage ( message ) ; } chrome . runtime . onMessage . addListener ( ( message ) => { if ( message . source === MESSAGE_SOURCE ) { window . postMessage ( message , window . location . origin ) ; } } ) ; interface ForwardDomEventToBackgroundArgs { payload : string ; method : MessageFromContentScript [ 'method' ] ; urlParam : string ; path : RouteUrls ; } function forwardDomEventToBackground ( { payload , method } ) { sendMessageToBackground ( { method , payload , source : MESSAGE_SOURCE , } ) ; } document . addEventListener ( DomEventName . authenticationRequest , ( ( event ) => { forwardDomEventToBackground ( { path : RouteUrls . Onboarding , payload : event . detail . authenticationRequest , urlParam : 'authRequest' , method : ExternalMethods . authenticationRequest , } ) ; } ) as EventListener ) ; document . addEventListener ( DomEventName . transactionRequest , ( ( event ) => { forwardDomEventToBackground ( { path : RouteUrls . Transaction , payload : event . detail . transactionRequest , urlParam : 'request' , method : ExternalMethods . transactionRequest , } ) ; } ) as EventListener ) ; const inpage = document . createElement ( 'script' ) ; inpage . src = chrome . runtime . getURL ( 'inpage.js' ) ; inpage . id = 'stacks-wallet-provider' ; document . body . appendChild ( inpage ) ;