@@ -9,7 +9,10 @@ import {
99 unrewriteUrl ,
1010 type URLMeta ,
1111 BareClient ,
12+ ScramjetServiceWorker ,
1213} from "@mercuryworkshop/scramjet/bundled" ;
14+ import { ElementType , type Handler , Parser } from "htmlparser2" ;
15+ import { type ChildNode , DomHandler , Element , Comment , Node } from "domhandler" ;
1316import * as tldts from "tldts" ;
1417
1518const ISOLATION_ORIGIN = import . meta. env . VITE_ISOLATION_ORIGIN ;
@@ -158,6 +161,8 @@ export class IsolatedFrame {
158161 }
159162}
160163
164+ const inject_script = "/page_inject.js" ;
165+
161166const methods = {
162167 async fetch (
163168 data : ScramjetFetchContext ,
@@ -178,6 +183,19 @@ const methods = {
178183 return [ await makeWasmResponse ( ) , undefined ] ;
179184 } else if ( data . rawUrl . pathname === cfg . files . all ) {
180185 return [ await makeAllResponse ( ) , undefined ] ;
186+ } else if ( data . rawUrl . pathname === inject_script ) {
187+ return [
188+ await fetch ( inject_script ) . then ( async ( x ) => {
189+ const text = await x . text ( ) ;
190+ return {
191+ body : text ,
192+ headers : { "Content-Type" : "application/javascript" } ,
193+ status : 200 ,
194+ statusText : "OK" ,
195+ } ;
196+ } ) ,
197+ undefined ,
198+ ] ;
181199 }
182200
183201 if ( data . destination === "document" || data . destination === "iframe" ) {
@@ -220,6 +238,26 @@ const methods = {
220238
221239 // TODO fix eventtarget jank
222240 const tgt = new EventTarget ( ) ;
241+ tgt . addEventListener ( "htmlPostRewrite" , ( e : any ) => {
242+ const handler = e . handler as DomHandler ;
243+ function findhead ( node : Element ) : Element | null {
244+ if ( node . type === ElementType . Tag && node . name === "head" ) {
245+ return node as Element ;
246+ } else if ( node . childNodes ) {
247+ for ( const child of node . childNodes ) {
248+ const head = findhead ( child as Element ) ;
249+ if ( head ) return head ;
250+ }
251+ }
252+
253+ return null ;
254+ }
255+
256+ const head = findhead ( handler . root as Node as Element ) ! ;
257+ console . log ( head ) ;
258+ head . children . unshift ( new Element ( "script" , { src : inject_script } ) ) ;
259+ } ) ;
260+
223261 const fetchresponse = await handleFetch . call (
224262 tgt as any ,
225263 data ,
0 commit comments