0.24.8 • Published 8 months ago

@nyanator/chrome-ext-utils v0.24.8

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

Version License: MIT

chrome-ext-utils

Chrome拡張のユーティリティクラスライブラリ。tsyringeによるコンストラクタインジェクションに対応します。

主要な機能:

  • AES暗号化されたコンテキスト通信に対応。

  • IndexedDBなどの外部依存の抽象化層を設定することで、アプリケーションを外部依存と切り離します。

Setup

Install

$ npm i @nyanator/chrome-ext-utils --save-dev

manifest.jsonのバージョン3に対応しています。permissionsに"tabs"、"storage"、"alarms"の指定が必要です。 また、cryptokeyファイルにランダムなUUIDを保存して"web_accessible_resources"に追加してください。 暗号化通信の鍵として利用します。

{
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "js": ["content.js"],
      "run_at": "document_start"
    }
  ],
  "description": "Web Develop Tools for ChatGPT",
  "manifest_version": 3,
  "permissions": ["tabs", "storage", "alarms"],
  "web_accessible_resources": [
    {
      "matches": ["https://chat.openai.com/*"],
      "resources": ["cryptokey"]
    }
  ]
}

Run tests

npm run test

API

initializeDIContainer(arg: { databaseName?: string; storeName?: string; allowedOrigins: string[]; }): Promise<MessageData | void>

tsyringe DIコンテナを初期化してメッセージングクラスや各種機能を登録します。

databaseName

Optional | string IndexedDBの初期化に使用するデータベース名称。

storeName

Optional | string IndexedDBの初期化に使用するストア名称。

allowedOrigins

Optional | string[] メッセージングクラスがデータの送受信を許可するオリジンの一覧。

Example

// entrypoint.ts
import { initializeDIContainer } from "@nyanator/chrome-ext-utils";

initializeDIContainer({
  databaseName: "databaseName",
  storeName: "storeName",
  allowedOrigins: ["https://www.example.com/"],
});
// module-class.ts
import {
  DatabaseAgent,
  Logger,
  RuntimeMessageAgent,
  WindowMessageAgent,
} from "@nyanator/chrome-ext-utils";
import { inject, injectable } from "tsyringe";

@injectable()
export class ModuleClass {
  constructor(
    @inject("CrossDispatcher") crossDispatcher: CrossDispatcher,
    @inject("DatabaseAgent") databaseAgent: DatabaseAgent,
    @inject("Logger") logger: Logger,
    @inject("RuntimeMessageAgent") runtimeMessageAgent: RuntimeMessageAgent,
    @inject("WindowMessageAgent") windowMessageAgent: WindowMessageAgent,
    ) { }
}

RuntimeMessageAgent

暗号化されたランタイムメッセージの送受信を管理します。chrome.runtime.sendMessageのラップクラス。

Methods

sendMessage(channel: string, message?: MessageData, tabId?: number): Promise<MessageData | void>

暗号化されたランタイムメッセージを送信します。指定したchannelへメッセージを送信します。tabIdが指定されている場合、そのIDのタブにメッセージを送信します。

channel

Require | string 送信先を識別する文字列キー。

message

Optional | MessageData 送信する本文データ。この部分がAES暗号化されます。

tabId

Optional | number 送信先のタブID。バックグラウンドスクリプトからコンテンツスクリプトへ送信する際などに指定します。


addListener(channel: string, listener: (messageData: MessageData) => Promise<MessageData | void> | void): void

指定したchannelでのランタイムメッセージを受信し、復号化してリスナー関数に渡します。

channel

Require | string 受信データをフィルタリングするための文字列キー。

listener

Require | fn チャンネルがデータを受信したときに実行されるリスナー。

Example

// content.ts
import {
  initializeDIContainer,
  RuntimeMessageAgent
} from "@nyanator/chrome-ext-utils";
import { container } from "tsyringe";

initializeDIContainer({
  allowedOrigins: ["https://www.example.com/"],
});

const messageAgent = container.resolve<RuntimeMessageAgent>("RuntimeMessageAgent");
messageAgent.sentMessage("channel", {message: "hello message"});
// background.ts
import {
  initializeDIContainer,
  RuntimeMessageAgent
} from "@nyanator/chrome-ext-utils";
import { container } from "tsyringe";

initializeDIContainer({
  allowedOrigins: ["https://www.example.com/"],
});

const messageAgent = container.resolve<RuntimeMessageAgent>("RuntimeMessageAgent");
messageAgent.addListener("channel", (messageData) => {
  console.log(messageData.message);
});

WindowMessageAgent

暗号化されたウィンドウメッセージの送受信を管理します。winodow.postMessageのラップクラス。

Methods

postMessage(target: Window, targetOrigin: string, channel: string, message?: MessageData,): Promise<void>

暗号化されたウィンドウメッセージを送信します。指定したウィンドウ、オリジンのchannelへメッセージを送信します。

target

Require | Window 送信先ウィンドウ。

targetOrigin

Require | string 送信先オリジン。initializeDIContainerで許可したオリジン以外を指定すると例外が発生します。

channel

Require | string 送信先を識別する文字列キー。

message

Optional | MessageData 送信する本文データ。この部分がAES暗号化されます。


addListener(channel: string, listener: (event: MessageData) => void): void

指定したchannelでのウィンドウメッセージを受信し、復号化してリスナー関数に渡します。

channel

Require | string 受信データをフィルタリングするための文字列キー。

listener

Require | fn チャンネルがデータを受信したときに実行されるリスナー。

Example

// content.ts
import {
  initializeDIContainer,
  WindowMessageAgent
} from "@nyanator/chrome-ext-utils";
import { container } from "tsyringe";

initializeDIContainer({
  allowedOrigins: ["https://www.example.com/"],
});

const messageAgent = container.resolve<WindowMessageAgent>("WindowMessageAgent");
messageAgent.addListener("channel", (messageData) => {
  console.log(messageData.message);
});
// iframe.ts
import {
  initializeDIContainer,
  WindowMessageAgent
} from "@nyanator/chrome-ext-utils";
import { container } from "tsyringe";

initializeDIContainer({
  allowedOrigins: ["https://www.example.com/"],
});

const messageAgent = container.resolve<WindowMessageAgent>("WindowMessageAgent");
messageAgent.postMessage(window.parent, "https://www.example.com/", "channel", {message: "hello message"});

Etc

  • CrossDispathcer 片付けされたイベントエミッター

  • CryptoAgent 暗号化インターフェース

  • ErrorObserver 未処理例外をユーザーに通知する機能を提供

  • And More...


Author

👤 nyanator

📝 License

Copyright © 2023 nyanator.

This project is MIT licensed.


This README was generated with ❤️ by readme-md-generator

ababacornacorn-globalsacorn-jsxacorn-walkagent-baseajvansi-escapesansi-regexansi-sequence-parseransi-stylesanymatchargargparsearray-buffer-byte-lengtharray-includesarray-timsortarray-unionarray.prototype.findlastindexarray.prototype.flatarray.prototype.flatmaparraybuffer.prototype.sliceasynckitavailable-typed-arraysbabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbase64-arraybuffer-es6base64-jsblbrace-expansionbracesbrowser-process-hrtimebrowserslistbserbufferbuffer-fromcall-bindcallsitescamelcasecaniuse-litechalkchar-regexchardetci-infocjs-module-lexercli-cursorcli-spinnerscli-widthcliuiclonecocollect-v8-coveragecolor-convertcolor-namecombined-streamcommandercomment-jsonconcat-mapconvert-source-mapcore-util-iscreate-requirecross-spawncrypto-jscssomcssstyledata-urlsdebugdecimal.jsdedentdeep-isdeepmergedefaultsdefine-propertiesdelayed-streamdetect-newlinediffdiff-sequencesdir-globdoctrinedomexceptiondrangeelectron-to-chromiumemitteryemoji-regexerror-exes-abstractes-set-tostringtages-shim-unscopableses-to-primitiveescaladeescape-string-regexpescodegeneslint-import-resolver-nodeeslint-module-utilseslint-rule-composereslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsexecaexitexpectexternal-editorfast-deep-equalfast-globfast-json-stable-stringifyfast-levenshteinfastqfb-watchmanfiguresfile-entry-cachefill-rangefind-upflat-cacheflattedfor-eachform-datafs.realpathfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-package-typeget-streamget-symbol-descriptionglobglob-parentglobal-prefixglobalsglobalthisglobbygopdgraceful-fsgraphemerhashas-bigintshas-flaghas-own-prophas-property-descriptorshas-protohas-symbolshas-tostringtaghtml-encoding-snifferhtml-escaperhttp-proxy-agenthttps-proxy-agenthuman-signalsiconv-liteieee754ignoreimport-freshimport-localimurmurhashinflightinheritsiniinquirerinternal-slotis-array-bufferis-arrayishis-bigintis-boolean-objectis-callableis-core-moduleis-date-objectis-extglobis-fullwidth-code-pointis-generator-fnis-globis-interactiveis-negative-zerois-numberis-number-objectis-path-insideis-potential-custom-element-nameis-regexis-shared-array-bufferis-streamis-stringis-symbolis-typed-arrayis-typedarrayis-unicode-supportedis-weakrefisarrayisexeistanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsjest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-jasmine2jest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-serializerjest-snapshotjest-utiljest-validatejest-watcherjest-workerjs-tokensjs-yamljsdomjsescjson-bufferjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson5jsonc-parserkeyvkind-ofkleurlevenlevnlines-and-columnslocate-pathlodashlodash.mergelog-symbolslru-cachelunrmake-dirmake-errormakeerrormarkedmerge-streammerge2micromatchmime-dbmime-typesmimic-fnminimatchminimistmsmute-streamnatural-comparenode-int64node-releasesnormalize-pathnpm-run-pathnwsapiobject-inspectobject-keysobject.assignobject.fromentriesobject.groupbyobject.valuesonceonetimeoptionatororaos-tmpdirp-limitp-locatep-tryparent-moduleparse-jsonparse5path-existspath-is-absolutepath-keypath-parsepath-typepicocolorspicomatchpiratespkg-dirprelude-lsprettierpretty-formatpromptspslpunycodequerystringifyqueue-microtaskrandexpreact-isreadable-streamrealistic-structured-cloneregexp.prototype.flagsrepeat-stringrequire-directoryrequires-portresolveresolve-cwdresolve-fromresolve.exportsrestore-cursorretreusifyrimrafrun-asyncrun-parallelrxjssafe-array-concatsafe-buffersafe-regex-testsafer-buffersaxessemvershebang-commandshebang-regexshikiside-channelsignal-exitsisteransislashsource-mapsource-map-supportsprintf-jsstack-utilsstring_decoderstring-lengthstring-widthstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstrip-ansistrip-bomstrip-final-newlinestrip-json-commentssupports-colorsupports-hyperlinkssupports-preserve-symlinks-flagsymbol-treeterminal-linktest-excludetext-tablethroatthroughtmptmplto-fast-propertiesto-regex-rangetough-cookietr46ts-api-utilstsconfig-pathstslibtype-checktype-detecttype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarray-to-buffertypesontypeson-registryunbox-primitiveuniversalifyupdate-browserslist-dburi-jsurl-parseutil-deprecatev8-compile-cache-libv8-to-istanbulvscode-onigurumavscode-textmatew3c-hr-timew3c-xmlserializerwalkerwcwidthwebidl-conversionswhatwg-encodingwhatwg-mimetypewhatwg-urlwhichwhich-boxed-primitivewhich-typed-arraywrap-ansiwrappywrite-file-atomicwsxml-name-validatorxmlcharsy18nyallistyargsyargs-parserynyocto-queue
0.24.8

8 months ago

0.24.7

8 months ago

0.24.6

8 months ago

0.24.5

8 months ago

0.24.4

8 months ago

0.24.3

8 months ago

0.24.2

8 months ago

0.24.1

8 months ago

0.24.0

8 months ago

0.23.9

8 months ago

0.23.8

8 months ago

0.23.7

8 months ago

0.23.6

8 months ago

0.23.5

8 months ago

0.23.3

8 months ago

0.23.2

8 months ago

0.23.1

8 months ago

0.23.0

8 months ago

0.22.9

8 months ago

0.22.8

8 months ago

0.22.7

8 months ago

0.22.6

8 months ago

0.22.5

8 months ago

0.22.4

8 months ago

0.22.3

8 months ago

0.22.2

8 months ago

0.22.1

8 months ago

0.22.0

8 months ago

0.21.9

8 months ago

0.21.8

8 months ago

0.21.7

8 months ago

0.21.6

8 months ago

0.21.5

8 months ago

0.21.4

8 months ago

0.21.3

8 months ago

0.21.2

8 months ago

0.21.1

8 months ago

0.21.0

8 months ago

0.20.0

8 months ago

0.19.0

8 months ago

0.18.0

8 months ago

0.17.0

8 months ago

0.16.0

8 months ago

0.15.0

8 months ago

0.14.0

8 months ago

0.13.0

8 months ago

0.12.0

8 months ago

0.11.0

8 months ago

0.10.0

8 months ago