Skip to content

Instantly share code, notes, and snippets.

View EduardoAC's full-sized avatar

Eduardo Aparicio Cardenes EduardoAC

View GitHub Profile
@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
@EduardoAC
EduardoAC / cookieInitInServiceWorker.ts
Last active February 11, 2024 08:27
Example retrieving language from client-side cookie when initialising service worker
try {
const languageCookieFromWebApp: chrome.cookies.Cookie | null =
await chrome.cookies.get({
url: `${your - webApp - url}`, // Remember taht URL change for localhost and live
name: "{your-webApp-name}-language",
});
if (languageCookieFromWebApp) {
const language = languageCookieFromWebApp.value
if (language) {
chrome.storage.local.set({ language });
@EduardoAC
EduardoAC / exampleSettingLanguageWebApp.ts
Created February 11, 2024 08:11
Example setting up language on the Web App allowing real-time sync with the browser extension
function onAuthSuccess(user: User) {
// Initialise your client environment after authentication
//...
setLanguageCookie(user.language)
i18n.changeLanguage(user.language)
}
// ...
function onUserLanguageChange(language: LanguagesSupported) {
// ...
setLanguageCookie(language)
@EduardoAC
EduardoAC / setLanguageCookie.ts
Created February 11, 2024 08:02
Persist Language in a client-side cookie using js-cookie library
import Cookies from "js-cookie"
const languageCookieKey = "{your-webApp-name}-language"
const cookieOptions = {
// ...
// Only set secure if we are running on an https environment.
// secure: true => force cookie to be only readable by https requests.
secure: window?.location?.protocol === "https:",
}
@EduardoAC
EduardoAC / broadcastingMessageAllLoadedTabs.ts
Created November 5, 2023 10:12
Chrome Extension: Broadcasting a message to all tabs currently loaded in the browser.
// Message and response are define in https://gist.github.com/EduardoAC/000b1e39a6ec10a892e7c6cd93730a53
export function broadcastMessageAllLoadedTabs<T>(message: Message<T>) {
// Get all tabs not discarded - it can be optimise further
chrome.tabs.query({ discarded: false }, (tabs) => {
tabs.forEach(({ id, status }) => {
if(status !== "unloaded") {
sendMessage(id, message)
}
})
})