@@ -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,10 @@ export class SandpackStatic extends SandpackClient {
5054 content ,
5155 options . externalResources
5256 ) ;
57+ content = this . injectContentIntoHead (
58+ content ,
59+ `<script>${ consoleHook } </script>`
60+ ) ;
5361 } catch ( err ) {
5462 console . error ( "Runtime injection failed" , err ) ;
5563 }
@@ -79,6 +87,11 @@ export class SandpackStatic extends SandpackClient {
7987 "accelerometer; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; clipboard-write;"
8088 ) ;
8189 }
90+
91+ this . eventListener = this . eventListener . bind ( this ) ;
92+ if ( typeof window !== "undefined" ) {
93+ window . addEventListener ( "message" , this . eventListener ) ;
94+ }
8295 }
8396
8497 private injectContentIntoHead (
@@ -166,6 +179,21 @@ export class SandpackStatic extends SandpackClient {
166179 } ) ;
167180 }
168181
182+ // Handles message windows coming from iframes
183+ private eventListener ( evt : MessageEvent ) : void {
184+ // skip events originating from different iframes
185+ if ( evt . source !== this . iframe . contentWindow ) {
186+ return ;
187+ }
188+
189+ const message = evt . data ;
190+ if ( ! message . codesandbox ) {
191+ return ;
192+ }
193+
194+ this . dispatch ( message ) ;
195+ }
196+
169197 /**
170198 * Bundler communication
171199 */
@@ -187,5 +215,6 @@ export class SandpackStatic extends SandpackClient {
187215
188216 public destroy ( ) : void {
189217 this . emitter . cleanup ( ) ;
218+ window . removeEventListener ( "message" , this . eventListener ) ;
190219 }
191220}
0 commit comments