1+ browser . webRequest . onHeadersReceived . addListener (
2+ function ( details ) {
3+ let cookiesHeaders = details . responseHeaders . filter (
4+ ( header ) => header . name . toLowerCase ( ) === "set-cookie"
5+ ) ;
6+
7+ if ( cookiesHeaders . length === 0 ) {
8+ return ;
9+ }
10+
11+ let cookies = cookiesHeaders [ 0 ] . value ;
12+
13+ if ( ! cookies ) {
14+ return ;
15+ }
16+
17+ // cookies is a single string, e.g. "sampleCookie=sampleValue; Path=\/\nsampleCookie2=sampleValue2; Path=\/"
18+ // We need to split and parse it to a single dictionary
19+
20+ // Parse cookies
21+ let cookieDict = { } ;
22+ cookies . split ( "\n" ) . forEach ( ( cookie ) => {
23+ let cookieParts = cookie . split ( ";" ) [ 0 ] . split ( "=" ) ;
24+ let cookieName = cookieParts [ 0 ] . trim ( ) ;
25+ let cookieValue = cookieParts [ 1 ] . trim ( ) ;
26+ cookieDict [ cookieName ] = cookieValue ;
27+ } ) ;
28+
29+ // Send cookies back to the app (GeckoView) via messaging
30+ browser . runtime . sendNativeMessage ( "gecko" , {
31+ event : "cookies" ,
32+ cookies : cookieDict ,
33+ } ) ;
34+ } ,
35+ { urls : [ "<all_urls>" ] } , // Intercept all URLs
36+ [ "responseHeaders" ]
37+ ) ;
38+
39+ browser . webNavigation . onDOMContentLoaded . addListener ( function ( details ) {
40+ if ( details . frameId === 0 ) { // Ensure it's the top-level frame
41+ // Inject a script to fetch the outerHTML of the current document
42+ browser . tabs . executeScript ( details . tabId , {
43+ code : "document.documentElement.outerHTML"
44+ } ) . then ( result => {
45+ if ( result && result . length > 0 ) {
46+ const htmlBody = result [ 0 ] ; // The outerHTML of the page
47+
48+ // Send the HTML content and cookies to the native app
49+ browser . runtime . sendNativeMessage ( "gecko" , {
50+ event : "html_body" ,
51+ html : htmlBody
52+ } ) ;
53+
54+ } else {
55+ browser . runtime . sendNativeMessage ( "gecko" , {
56+ event : "No results when getting outerHTML" ,
57+ } ) ;
58+ }
59+ } ) . catch ( err => {
60+ browser . runtime . sendNativeMessage ( "gecko" , {
61+ event : "Execute script error: " + err . toString ( ) ,
62+ } ) ;
63+ } )
64+ }
65+ } ) ;
0 commit comments