Skip to content

Commit

Permalink
Require initialization to set up listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
Grant Cleary committed Apr 3, 2024
1 parent 337ee9c commit 0f945df
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/host/host.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
let initialized = false;

const allowedFrames = new Map();
const registeredPlugins = new Map();

window.addEventListener('message', e => handleContextRequestMessage(e));
document.addEventListener('lms-context-request', e => handleContextRequestEvent(e));

function handleContextRequest(type, options, subscribe) {
const plugin = registeredPlugins.get(type);
if (!plugin) {
Expand Down Expand Up @@ -66,7 +65,20 @@ function sendChangeEvent(type, changedValues) {
});
}

export function initialize() {
if (initialized) return;

window.addEventListener('message', handleContextRequestMessage);
document.addEventListener('lms-context-request', handleContextRequestEvent);

initialized = true;
}

export function allowFrame(frame, origin) {
if (!initialized) {
throw new Error(`lms-context-provider: Can't register frame with id ${frame.id}. Context provider host has not been initialized.`);
}

if (allowedFrames.has(frame)) {
throw new Error(`lms-context-provider: A frame with id ${frame.id} has already been registered with this host.`);
}
Expand All @@ -75,6 +87,10 @@ export function allowFrame(frame, origin) {
}

export function registerPlugin(name, tryGetCallback, subscriptionCallback) {
if (!initialized) {
throw new Error(`lms-context-provider: Can't register plugin with name ${name}. Context provider host has not been initialized.`);
}

if (registeredPlugins.has(name)) {
throw new Error(`lms-context-provider: A plugin with name ${name} has already been registered with this host.`);
}
Expand Down

0 comments on commit 0f945df

Please sign in to comment.