Skip to content

Instantly share code, notes, and snippets.

@bluepnume
Last active Sep 19, 2021
Embed
What would you like to do?
// 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