Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@ export const createMessageDispatcherMiddleware = ({ senderURL, parentURL, target

type MessageRecieverOptions = {
allowedURLs: string[];
allowedTypes?: string[];
};

export const createMessageRecieverMiddleware = ({ allowedURLs }: MessageRecieverOptions) => {
export const createMessageRecieverMiddleware = ({ allowedURLs, allowedTypes = [] }: MessageRecieverOptions) => {
const messageToActionHandler = createMessageToActionHandler({
allowedURLs
allowedURLs,
allowedTypes
});

return MessageRecieverMiddleware({ messageToActionHandler });
Expand Down
8 changes: 7 additions & 1 deletion src/messaging/message-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const isValidAction = (action: any): boolean => isString(action.type);

type Dependencies = {
allowedURLs: string[];
allowedTypes?: string[];
}

export type ActionHandler = (action: any) => void;
Expand All @@ -26,17 +27,22 @@ export type MessageHandler = (ev: MessageEvent) => void;

export type MessageToActionHandler = (fn: ActionHandler) => MessageHandler;

export const createMessageToActionHandler = ({ allowedURLs }: Dependencies): MessageToActionHandler => {
export const createMessageToActionHandler = ({allowedURLs: allowedURLs, allowedTypes: allowedTypes = []}: Dependencies): MessageToActionHandler => {

const isValidOrigin = (origin: string): boolean => {
return allowedURLs.some(url => url.includes(origin));
};

const isValidType = (action: string): boolean => {
return allowedTypes !== undefined ? allowedTypes.some(type => type.includes(action)) : true;
};

return (fn: ActionHandler): MessageHandler => (ev: MessageEvent) => {
const origin = getEventOrigin(ev);
if (!isValidOrigin(origin)) { return; }
const action = readAction(ev);
if (!isValidAction(action)) { return; }
if (!isValidType(action)) { return; }
fn(action);
};
};