Skip to content

Constrain dispatch to specific action types. #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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);
};
};