fregante / webext-tools

Utility functions for WebExtensions
https://npm.im/webext-tools
MIT License
18 stars 1 forks source link

What generic/common functions could be added? #1

Open fregante opened 2 years ago

fregante commented 2 years ago

Ideas for little functions welcome. Currently I'm just looking at tiny reusable functions that I already wrote in other repositories.

fregante commented 2 years ago

Extracted from https://github.com/pixiebrix/pixiebrix-extension/pull/2317

function printf(string: string, arguments_: string[]): string {
  // eslint-disable-next-line unicorn/no-array-reduce -- Short and already described by "printf"
  return arguments_.reduce(
    (message, part) => message.replace("%s", part),
    string
  );
}
/** Wrapper around the dev tools’ `eval` function to throw proper errors */
export async function devToolsEval(code: string) {
  const [response, error] = await browser.devtools.inspectedWindow.eval(code);

  // Handle Dev Tools API error response
  // https://developer.chrome.com/docs/extensions/reference/devtools_inspectedWindow/#method-eval
  // https://github.com/pixiebrix/pixiebrix-extension/pull/999#discussion_r684370643
  if (!response && error?.isError) {
    throw new Error(printf(error.description, error.details));
  }

  return response;
}
fregante commented 1 year ago

https://github.com/fregante/webext-content-scripts/blob/707825400b2a2984901301c5e053a9265282e883/index.ts#L196-L207