Skip to content

Instantly share code, notes, and snippets.

@Moizsohail
Created March 3, 2022 19:28
Show Gist options
  • Save Moizsohail/32ae540df1cad4bdd9d09186ea3a8110 to your computer and use it in GitHub Desktop.
Save Moizsohail/32ae540df1cad4bdd9d09186ea3a8110 to your computer and use it in GitHub Desktop.
Chrome Extension In React With NPM Modules: Part 3 ii
import {
ChromeMessage,
ChromeMessageExecute,
MessageResponse,
MessageTypes,
} from "../types";
import { say } from "cowsay";
const messagesFromReactAppListener = (
message: ChromeMessage,
sender: chrome.runtime.MessageSender,
sendResponse: MessageResponse
) => {
switch (message.type) {
case MessageTypes.execute:
const { text } = message as ChromeMessageExecute;
const newText = say({
text: text,
e: "oO",
T: "U ",
});
const images = document.querySelectorAll("img");
[...images].forEach((node) => {
const p = document.createElement("p");
p.innerHTML = newText;
p.style.whiteSpace = "pre";
node.replaceWith(p);
});
chrome.storage.sync.set({ mooText: text }); //new
break;
// ---- new ----
case MessageTypes.shortcutExecute:
chrome.storage.sync.get("mooText").then((obj) => {
const text = Object.values(obj)[0];
const newText = say({
text: text,
e: "oO",
T: "U ",
});
const images = document.querySelectorAll("img");
[...images].forEach((node) => {
const p = document.createElement("p");
p.innerHTML = newText;
p.style.whiteSpace = "pre";
node.replaceWith(p);
});
});
break;
// ----- new-end -----
}
};
const main = () => {
console.log("[content.ts] Running");
chrome.runtime.onMessage.addListener(messagesFromReactAppListener);
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment