Skip to content

Instantly share code, notes, and snippets.

View EduardoAC's full-sized avatar

Eduardo Aparicio Cardenes EduardoAC

View GitHub Profile
@EduardoAC
EduardoAC / eventHandler.ts
Last active June 7, 2024 12:08
Chrome Extension - Site Page Review - Message Handler. The goal of this function is to orchestrate the messages received by the content scripts and proxy them to the right handler.
import { MessageRate } from "../../types/message.types"
import { ratingMessageHandler } from "./onMessageHandlers/ratingMessageHandler"
export function messageHandler(
message: Message,
sender: chrome.runtime.MessageSender,
sendResponse: SendResponseCallback,
) {
if (sender.tab && message.type) {
switch (message.type) {
@EduardoAC
EduardoAC / ratingMessageHandler.ts
Created June 6, 2024 08:03
Chrome extension - site page review - rating message handler - The goal of this function is to manage all the messages received by the content scripts regarding rating
import { MessageRate } from "../../../types/message.types"
async function updateCacheRating(
sendResponse: SendResponseCallback,
data?: MessageRate,
): Promise<void> {
if (typeof data?.url === "string") {
try {
await chrome.storage.local.set({ [data.url]: data.rate })
return sendResponse({ statusCode: 200 })
@EduardoAC
EduardoAC / sendMessage.test.ts
Created June 6, 2024 07:57
Chrome extension - testing message handler using jest-chrome for Chrome API mocking
/* eslint-disable @typescript-eslint/no-explicit-any */
import { JestChrome } from "jest-chrome/types/jest-chrome"
import { sendMessage } from "./sendMessage"
describe("sendMessage", () => {
it("should send the message correctly", async () => {
const message: Message = { type: "rating", subType: "get" }
const response: MessageResponse = { statusCode: 200, data: 2 }
const jestChrome = chrome as any as JestChrome
@EduardoAC
EduardoAC / site-review-extension-rating.tsx
Created June 6, 2024 07:32
Site review extension - Rating component
import { MessageRate } from "../../../types/message.types"
import { sendMessage } from "../../messages/sendMessage"
import { clearUrlParams } from "../..//utils/url"
import "./Rating.css"
import { useCallback, useEffect, useState } from "react"
const totalRating = Array.from({ length: 5 }, (_, index) => index + 1)
export function Rating() {
const [rating, setRating] = useState<number>(0)
@EduardoAC
EduardoAC / cookieOnChangeListenerBackground.ts
Created February 11, 2024 10:28
Cookie on change listener within the background script
// Cookie listener for onChange events in the background.ts
// cookiesHandler can be found in https://gist.github.com/EduardoAC/35ba733a64854993483ab543de066aa4
chrome.cookies.onChanged.addListener(cookiesHandler)
@EduardoAC
EduardoAC / checkLanguageCookieChangesWebApp.ts
Created February 11, 2024 08:59
Web app polling function designed to monitor language changes in the browser extension for real-time synchronization.
import Cookies from "js-cookie";
// Function to check for changes in cookies
function checkLanguageCookieChanges() {
// Get the current value of the cookie
const currentLanguage = Cookie.get("{your-webApp-name}-language}");
// Compare with the previous value
if (currentLanguage !== checkLanguageCookieChanges.previousLanguage) {
// Cookie has changed
i18n.changeLanguage(currentLanguage);
@EduardoAC
EduardoAC / languageMessageHandler.tsx
Created February 11, 2024 08:47
Language message handler within the content script for a browser extension built using React + event-driven model.
function initMessageHandler() {
// ...
useEffect(() => {
// Listening for updates by the service worker
chrome.runtime.onMessage.addListener(handleMessageListener);
return () => {
chrome.runtime.onMessage.removeListener(handleMessageListener);
};
}, []);
}
@EduardoAC
EduardoAC / updateLanguage.ts
Last active February 11, 2024 10:29
Helper to manage language updates by broadcasting the language change, along with the new translation, to the content scripts.
export async function updateLanguage(language: LanguagesSupported) {
chrome.storage.local.set({ language });
broadcastMessageAllTabs({
type: "languageUpdated",
data: {
language: language,
translations: i18n.getDataByLanguage(language),
},
});
}
@EduardoAC
EduardoAC / cookiesHandler.ts
Created February 11, 2024 08:38
Handling cookie changes events trigger by chrome.cookies.onChanged.addListener
export async function cookiesHandler({ cause, cookie, removed }: chrome.cookies.CookieChangeInfo) {
// We are interested in cookies which are set/updated in the browser
const hasUpdateCookie = !removed && cause === "explicit";
// We are interested when the cookie is removed from the browser
const hasClearCookie = removed && (cause === "explicit" || cause === "expired_overwrite");
const isRelevantCookieUpdate = hasUpdateCookie || hasClearCookie;
// We monitor only cookies within the our webApp domain
const yourWebAppDomain = extractDomain(`${your-webApp-url}`);
// Check for the language cookie belonging to your-webApp-url domain
@EduardoAC
EduardoAC / extractValueFromCookie.ts
Created February 11, 2024 08:19
Helper function to extract cookie value field using consider the cookie stores an object using RFC-6265 standard
export function extractValueFromCookie<T>(cookie: chrome.cookies.Cookie): T | undefined {
try {
// Follow standard parsing RFC-6265 -> https://github.com/js-cookie/js-cookie/blob/master/src/converter.mjs
const decodeCookieValue = cookie.value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)
return JSON.parse(decodeCookieValue)
} catch (e) {
console.error("Cookie couldn't be parse")
console.error(e)
}
return undefined