@@ -15,6 +15,10 @@ import type { SandpackNodeMessage } from "../node/types";
1515
1616import { insertHtmlAfterRegex , readBuffer , validateHtml } from "./utils" ;
1717
18+ // get the bundled file, which contains all dependencies
19+ // @ts -ignore
20+ import consoleHook from "../../inject-scripts/dist/consoleHook.js" ;
21+
1822export class SandpackStatic extends SandpackClient {
1923 private emitter : EventEmitter ;
2024 private previewController : PreviewController ;
@@ -50,6 +54,9 @@ export class SandpackStatic extends SandpackClient {
5054 content ,
5155 options . externalResources
5256 ) ;
57+ content = this . injectScriptIntoHead ( content , {
58+ script : consoleHook ,
59+ } ) ;
5360 } catch ( err ) {
5461 console . error ( "Runtime injection failed" , err ) ;
5562 }
@@ -80,6 +87,11 @@ export class SandpackStatic extends SandpackClient {
8087 ) ;
8188 }
8289
90+ this . eventListener = this . eventListener . bind ( this ) ;
91+ if ( typeof window !== "undefined" ) {
92+ window . addEventListener ( "message" , this . eventListener ) ;
93+ }
94+
8395 // Dispatch very first compile action
8496 this . updateSandbox ( ) ;
8597 }
@@ -137,6 +149,21 @@ export class SandpackStatic extends SandpackClient {
137149 return this . injectContentIntoHead ( content , tagsToInsert ) ;
138150 }
139151
152+ private injectScriptIntoHead (
153+ content : FileContent ,
154+ opts : { script : string ; scope ?: Record < string , any > }
155+ ) : FileContent {
156+ const { script, scope = { } } = opts ;
157+ const scriptToInsert = `
158+ <script>
159+ const scope = ${ JSON . stringify ( scope ) } ;
160+ ${ script }
161+ </script>
162+ ` . trim ( ) ;
163+
164+ return this . injectContentIntoHead ( content , scriptToInsert ) ;
165+ }
166+
140167 public updateSandbox (
141168 setup = this . sandboxSetup ,
142169 _isInitializationCompile ?: boolean
@@ -169,6 +196,21 @@ export class SandpackStatic extends SandpackClient {
169196 } ) ;
170197 }
171198
199+ // Handles message windows coming from iframes
200+ private eventListener ( evt : MessageEvent ) : void {
201+ // skip events originating from different iframes
202+ if ( evt . source !== this . iframe . contentWindow ) {
203+ return ;
204+ }
205+
206+ const message = evt . data ;
207+ if ( ! message . codesandbox ) {
208+ return ;
209+ }
210+
211+ this . dispatch ( message ) ;
212+ }
213+
172214 /**
173215 * Bundler communication
174216 */
@@ -190,5 +232,8 @@ export class SandpackStatic extends SandpackClient {
190232
191233 public destroy ( ) : void {
192234 this . emitter . cleanup ( ) ;
235+ if ( typeof window !== "undefined" ) {
236+ window . removeEventListener ( "message" , this . eventListener ) ;
237+ }
193238 }
194239}
0 commit comments