Skip to content

Commit

Permalink
feat: add messages and receiver to the script
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewinci committed Mar 15, 2023
1 parent bfb30e0 commit d0916bc
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 2 deletions.
39 changes: 39 additions & 0 deletions src/messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// messages exchanged between the script and the popup window
// requests are messages from the pop up to the script
// responses are messages from the script to the pop up

/**
* Message from the pop-up to the script
* to check if the script is loaded in the page
*/
type PingRequest = { action: "ping" };
/**
* Reply to Ping from the script to pop-up
*/
type PingResponse = { action: "pong" };
/**
* Get the current drawing from the local store
*/
type GetDrawingRequest = { action: "get-drawing" };

/**
* Return the current drawing to the pop up
*/
type GetDrawingResponse = { action: "drawing"; data: any };

/**
* Set the current drawing in the local store
* with the data content
*/
type SetDrawingRequest = { action: "set-drawing"; data: any };

type SetDrawingResponse = { action: "drawing-set"; success: boolean };

/**
* Messages sent from the Pop up to the script page
*/
export type PopUpMessage = PingRequest | GetDrawingRequest | SetDrawingRequest;
/**
* Messages sent from the script to the pop up window
*/
export type ScriptMessage = PingResponse | GetDrawingResponse | SetDrawingResponse;
36 changes: 34 additions & 2 deletions src/script.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
// entry point for the content-script loaded in the web page
// the application running in the pop-up can communicate with this script

import { PopUpMessage, ScriptMessage } from "./messages";

// via chrome messaging
const LOCAL_STORAGE_KEY = "excalidraw";

export const sample = () => console.log("Hello");
// logic to handle messages from the extension popup
chrome.runtime.onMessage.addListener(function (
genericRequest,
_,
sendResponse
) {
const request = genericRequest as PopUpMessage;
const reply = (message: ScriptMessage) => sendResponse(message);
switch (request.action) {
case "ping":
reply({ action: "pong" });
break;
case "get-drawing":
reply({
action: "drawing",
data: localStorage.getItem(LOCAL_STORAGE_KEY),
});
break;
case "set-drawing":
localStorage.setItem(LOCAL_STORAGE_KEY, request.data);
reply({
action: "drawing-set",
success: true,
});
// refresh the page to load the new content
window.location.reload();
break;
}
});

sample();
export {};

0 comments on commit d0916bc

Please sign in to comment.