Skip to content

A template for browser extensions, based on react, and redux connectivity between popup and background.

License

Notifications You must be signed in to change notification settings

teafoot/browser-extension-template

 
 

Repository files navigation

Browser Extension Template

Home About Settings
home about settings

Table of Contents


Tech stack

User interface

Extension

State managment

Architecture

Core

Entities

import { Key } from "./key";

export class Fragment {
  constructor(
    readonly key: Key,
    readonly uri: string,
    readonly index: number
  ) {}
}

Use cases

  • Represent an isolated signle piece of your business actions: it’s what you can do with the application. Expect one use case for each business action
  • Pure business logic, plain code (except maybe some utils libraries)
  • The use case doesn’t know who triggered it and how the results are going to be presented.
  • More examples: (here)[https://github.com/puemos/hls-downloader/tree/master/src/core/src/use-cases]
import { Fragment } from "../entities";
import { ILoader } from "../services";

export const downloadSingleFactory = (loader: ILoader) => {
  const run = async (
    fragment: Fragment,
    fetchAttempts: number
  ): Promise<ArrayBuffer> => {
    const data = await loader.fetchArrayBuffer(fragment.uri, fetchAttempts);
    return data;
  };
  return run;
};

Services

export interface ILoader {
  fetchText(url: string, attempts?: number): Promise<string>;
  fetchArrayBuffer(url: string, attempts?: number): Promise<ArrayBuffer>;
}

Controllers

import { Epic } from "redux-observable";
import { of } from "rxjs";
import { filter, map, mergeMap } from "rxjs/operators";
import { RootAction, RootState } from "../adapters/redux/root-reducer";
import { jobsSlice } from "../adapters/redux/slices";
import { Dependencies } from "../services";

export const incDownloadStatusEpic: Epic<
  RootAction,
  RootAction,
  RootState,
  Dependencies
> = (action$, store$) =>
  action$.pipe(
    filter(jobsSlice.actions.incDownloadStatus.match),
    map((action) => action.payload.jobId),
    map((id) => ({ id, status: store$.value.jobs.jobsStatus[id] })),
    filter(({ status }) => Boolean(status)),
    filter(({ status }) => status!.done === status!.total),
    mergeMap(({ id }) => {
      return of(
        jobsSlice.actions.finishDownload({
          jobId: id,
        }),
        jobsSlice.actions.saveAs({
          jobId: id,
        })
      );
    })
  );

Store

WIP

Apps

Background

Listeners
import { tabs } from "webextension-polyfill";
import { createStore } from "@hls-downloader/core/lib/store/configure-store";
import { tabsSlice } from "@hls-downloader/core/lib/store/slices";

export function setTabListener(store: ReturnType<typeof createStore>) {
  tabs.onActivated.addListener(async (details) => {
    store.dispatch(
      tabsSlice.actions.setTab({
        tab: {
          id: details.tabId,
        },
      })
    );
  });
}
Services
type FetchFn<Data> = () => Promise<Data>;

async function fetchWithRetry<Data>(
  fetchFn: FetchFn<Data>,
  attempts: number = 1
): Promise<Data> {
  if (attempts < 1) {
    throw new Error("Attempts less then 1");
  }
  let countdown = attempts;
  while (countdown--) {
    try {
      return await fetchFn();
    } catch (e) {
      if (countdown < 1 && countdown < attempts) {
        const retryTime = 100;
        await new Promise((resolve) => setTimeout(resolve, retryTime));
      }
    }
  }
  throw new Error("Fetch error");
}

export async function fetchText(url: string, attempts: number = 1) {
  const fetchFn: FetchFn<string> = () => fetch(url).then((res) => res.text());
  return fetchWithRetry(fetchFn, attempts);
}

export async function fetchArrayBuffer(url: string, attempts: number = 1) {
  const fetchFn: FetchFn<ArrayBuffer> = () =>
    fetch(url).then((res) => res.arrayBuffer());
  return fetchWithRetry(fetchFn, attempts);
}
export const FetchLoader = {
  fetchText,
  fetchArrayBuffer,
};

Popup

The extension's popup app.

components - Shared components modules - Your app's features

src
├── components
│   ├── Navbar.stories.tsx
│   ├── Navbar.tsx
│   └── NavLink.tsx
├── modules
│   ├── About
│   │   ├── AboutController.ts
│   │   ├── AboutModule.tsx
│   │   └── AboutView.tsx
│   ├── Home
│   │   ├── HomeModule.tsx
│   │   ├── HomeView.stories.tsx
│   │   └── HomeView.tsx
│   └── Settings
│      ├── SettingsController.ts
│      ├── SettingsModule.tsx
│      └── SettingsView.tsx
├── index.tsx
├── App.tsx
├── setupTests.ts
└── theme.ts
Modules

Each module is separated into a controller with business logic, a view with UI only (no logic), and a module that glue them together.

Scripts

Script Job
./scripts/build.sh Build all the app and create a zip file.
./scripts/build-background.sh Build only the extension's background app.
./scripts/build-popup.sh Build only the extension's popup app.
./scripts/build-core.sh Build only the extension's core library.
./scripts/build-extension.sh Build all the extension's apps.
./scripts/clean.sh Clean the build dir.
./scripts/copy-assets.sh Copy the extension's non-code assets,
./scripts/dev.sh Build and watch for changes.
./scripts/storybook.sh Run Storybook for the extension's popup app

Development

Build

  1. Clone the repo
  2. Ensure you have node, npm installed
  3. Run sh ./scripts/build.sh
  4. Raw files will be at ./dist/
  5. The zip will be in ./extension-archive.zip

Design

  1. Run sh ./scripts/storybook.sh
  2. Work on the UI in src/extension/popup

Installation

  1. Download the zip file from the latest release
  2. Open chrome://extensions/
  3. Drop the zip file into the page
  4. Enjoy :)

Contributing

Contributing guideline

TL;DR

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

Contributor Covenant Code of Conduct

Code of Conduct guideline

License

The MIT License (MIT)

Copyright (c) 2022 Shy Alter

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

A template for browser extensions, based on react, and redux connectivity between popup and background.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 91.9%
  • Shell 3.5%
  • HTML 2.5%
  • JavaScript 2.1%