-
-
Save bluepnume/df6672cdccfbda6e45d2a0aef56c609c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In window A: | |
// ------------ | |
// Store the original functions which will be called remotely from another window | |
const originalFunctions = {}; | |
// "Serialize" a function by storing it in memory and returning its id | |
const serializeFunction = (func) => { | |
const functionUUID = uuidv4(); | |
serializedFunctions[functionUUID] = func; | |
return functionUUID; | |
}; | |
// Listen for a post message to call the serialized function from another window | |
postRobot.on('callSerializedFunction', ({ data ) => { | |
const { serializedFunctionUUID, args } = data; | |
const originalFunction = originalFunctions[serializedFunctionUUID]; | |
return originalFunction(...args); | |
}); | |
// Create a simple function | |
const sayHello = (person) => { | |
console.log(`Hello ${ person }!`); | |
}; | |
// Serialize that function down to an id | |
const serializedSayHelloUUID = serializeFunction(sayHello); | |
// Now `serializedSayHelloUUID` can be sent over to window B. | |
// In window B: | |
// ------------ | |
// "Deserialize" a function by creating a wrapper function which messages the original window | |
const deserializeFunction = (serializedFunctionUUID) => { | |
return (...args) => { | |
return postRobot.send(originalWindow, 'callSerializedFunction', { | |
serializedFunctionUUID, args | |
}); | |
}; | |
}; | |
// "Deserialize" the sayHello function | |
const sayHello = deserializeFunction(serializedSayHelloUUID); | |
// Call the sayHello function | |
sayHello('world'); | |
// End result: logs 'hello world' in the original window (Window A) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment