@@ -229,35 +229,25 @@ if (window.GMBridge === undefined) {
229229 // Load external dependencies
230230 await loader . loadScripts ( requireUrls ) ;
231231
232- // Wrap user code in IIFE with unsafeWindow
233- const wrappedCode = `(function() {
234- 'use strict';
235- const unsafeWindow = this;
236- ${ userCode }
237- }).call(window);
238- ` ;
239-
240- // Create and inject script element
241- const scriptElement = document . createElement ( "script" ) ;
242- scriptElement . setAttribute ( "data-script-id" , scriptId ) ;
243-
244- // Apply Trusted Types if available
245232 const policy = getTrustedTypesPolicy ( ) ;
246- let trustedCode = wrappedCode ;
247-
248233 if ( policy ) {
249- try {
250- trustedCode = policy . createScript ( wrappedCode ) ;
251- } catch ( error ) {
252- console . error ( "[GMBridge] Failed to create trusted script:" , error ) ;
253- }
234+ // With Trusted Types, we must use a script tag, which runs in the MAIN world.
235+ // This is a known limitation for ISOLATED world scripts.
236+ const wrappedCode = `(function() { 'use strict'; const unsafeWindow = this; ${ userCode } }).call(window);` ;
237+ const scriptElement = document . createElement ( "script" ) ;
238+ scriptElement . setAttribute ( "data-script-id" , scriptId ) ;
239+ scriptElement . textContent = policy . createScript ( wrappedCode ) ;
240+ (
241+ document . head ||
242+ document . documentElement ||
243+ document . body
244+ ) . appendChild ( scriptElement ) ;
245+ scriptElement . remove ( ) ;
246+ } else {
247+ // No Trusted Types, we can execute in the current world's scope.
248+ const run = new Function ( "unsafeWindow" , userCode ) ;
249+ run . call ( window , window ) ;
254250 }
255-
256- scriptElement . textContent = trustedCode ;
257- ( document . head || document . documentElement || document . body ) . appendChild (
258- scriptElement
259- ) ;
260- scriptElement . remove ( ) ;
261251 } catch ( error ) {
262252 console . error (
263253 `[GMBridge] Error executing user script ${ scriptId } :` ,
0 commit comments