@@ -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 }
@@ -79,6 +86,11 @@ export class SandpackStatic extends SandpackClient {
7986 "accelerometer; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; clipboard-write;"
8087 ) ;
8188 }
89+
90+ this . eventListener = this . eventListener . bind ( this ) ;
91+ if ( typeof window !== "undefined" ) {
92+ window . addEventListener ( "message" , this . eventListener ) ;
93+ }
8294 }
8395
8496 private injectContentIntoHead (
@@ -134,6 +146,21 @@ export class SandpackStatic extends SandpackClient {
134146 return this . injectContentIntoHead ( content , tagsToInsert ) ;
135147 }
136148
149+ private injectScriptIntoHead (
150+ content : FileContent ,
151+ opts : { script : string ; scope ?: Record < string , any > }
152+ ) : FileContent {
153+ const { script, scope = { } } = opts ;
154+ const scriptToInsert = `
155+ <script>
156+ const scope = ${ JSON . stringify ( scope ) } ;
157+ ${ script }
158+ </script>
159+ ` . trim ( ) ;
160+
161+ return this . injectContentIntoHead ( content , scriptToInsert ) ;
162+ }
163+
137164 public updateSandbox (
138165 setup = this . sandboxSetup ,
139166 _isInitializationCompile ?: boolean
@@ -166,6 +193,21 @@ export class SandpackStatic extends SandpackClient {
166193 } ) ;
167194 }
168195
196+ // Handles message windows coming from iframes
197+ private eventListener ( evt : MessageEvent ) : void {
198+ // skip events originating from different iframes
199+ if ( evt . source !== this . iframe . contentWindow ) {
200+ return ;
201+ }
202+
203+ const message = evt . data ;
204+ if ( ! message . codesandbox ) {
205+ return ;
206+ }
207+
208+ this . dispatch ( message ) ;
209+ }
210+
169211 /**
170212 * Bundler communication
171213 */
@@ -187,5 +229,8 @@ export class SandpackStatic extends SandpackClient {
187229
188230 public destroy ( ) : void {
189231 this . emitter . cleanup ( ) ;
232+ if ( typeof window !== "undefined" ) {
233+ window . removeEventListener ( "message" , this . eventListener ) ;
234+ }
190235 }
191236}
0 commit comments