export const setupCrossDomainCommunication = ( ) => { const iframe = document . body . appendChild ( document . createElement ( 'iframe' ) ) ; iframe . src = 'https://example.com/fakepage' ; iframe . style . display = 'none' ; window . addEventListener ( 'message' , ( messageEvent ) => { if ( messageEvent . origin !== 'https://example.com' ) { return ; } const data = String ( messageEvent . data ) ; if ( ! data . startsWith ( 'cpUserscriptSpeakNewQuestionsCrossDomain: ' ) ) { return ; } const message = data . match ( /: (.*)/ ) ! [ 1 ] ; for ( const callback of onMessageCallbacks ) { callback ( message ) ; } } ) ; const onMessageCallbacks = new Set < ( message : string ) => void > ( ) ; return { addMessageListener ( callback ) { onMessageCallbacks . add ( callback ) ; } , removeMessageListener ( callback ) { onMessageCallbacks . delete ( callback ) ; } , postMessage ( message ) { iframe . contentWindow ?. postMessage ( `cpUserscriptSpeakNewQuestionsCrossDomain: ${ message }` , '*' ) ; } , } ; } ;