Skip to content

Instantly share code, notes, and snippets.

@bluepnume
Last active September 19, 2021 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluepnume/df6672cdccfbda6e45d2a0aef56c609c to your computer and use it in GitHub Desktop.
Save bluepnume/df6672cdccfbda6e45d2a0aef56c609c to your computer and use it in GitHub Desktop.
// 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