0.1.1 • Published 5 years ago

@bumble/chrome v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

Chrome API with Promises

Make Chrome extensions easier with Promise based API options.

browserAction

Set multiple browser action properties at once.

Use browser actions to put icons in the main Google Chrome toolbar, to the right of the address bar. In addition to its icon, a browser action can have a tooltip, a badge, and a popup.

See the Chrome API docs and MDN.

Parameters

  • details Object Browser action properties to set.

Examples

browserAction({
  badgeText: 'something',
  icon: 'icon2.png',
  // badgeColor: '#666',
  // title: 'browser action!',
  // popup: 'popup.html',
}).then(() => {
  console.log('All the browser action properties were set.')
}).catch((error) => {
  console.error('Could not set a browser action property.')
})
browserAction.set({
  superGalactic: true,
}).catch((error) => {
  console.error('Invalid argument: Unrecognized browser action property.')
})

Returns Promise Resolves after all properties are set, rejects with reason if a property was not set.

setBadgeText

Set the badge text for the browser action. Omit the details object to clear text. See the Chrome API Docs and MDN.

Parameters

  • details Object Badge text options.
    • details.text (string | false) The text to set on the browser action badge.
    • details.tabId number? Set the badge text only for the given tab. The text is reset when the user navigates this tab to a new page.

Examples

browserAction.setBadgeText({ text: 'something' })

Returns Promise Resolves after badgetext has been set. Rejects if there was an error.

setBadgeColor

Set the badge background color for the browser action. See the Chrome API Docs and MDN.

Parameters

  • details Object Badge text options.
    • details.color string The hex value of the background color for the badge.
    • details.tabId number? Set the badge color only for the given tab.

Examples

// Bulma Red
browserAction.setBadgeColor({ color: '#FF3860' })
// Bulma Orange
browserAction.setBadgeColor({ color: '#FF470F' })
// Default - Bulma Blue
browserAction.setBadgeColor()

Returns Promise Resolves after badge background color has been set. Rejects if there was an error.

setTitle

Set the tooltip text for the browser action. Omit the details object to use the extension name. See the Chrome API Docs and MDN.

Parameters

  • details Object? Title text options.
    • details.title (string | null) The text to set on the browser action title. (optional, default null)
    • details.tabId number? Set the title text only for the given tab. The text is reset when the user navigates this tab to a new page.
    • details.windowId number? Set the title text only for the given window.

Examples

browserAction.setTitle({ title: 'something' })

Returns Promise Resolves after title has been set. Rejects if there was an error.

setIcon

Set the icon for the browser action. See Chrome API Docs and MDN.

Parameters

  • details Object Object: {path:string, tabId(optional)}.

Examples

browserAction.setIcon({path: 'icon-16.png'})

Returns Promise Resolves after icon has been set.

message

Message

Use to send messages between documents (from background to content script, or vice-versa).

Type: Object

Properties

  • greeting string A constant to identify the message type.
  • tabId number? Identifies the tab to send the message to.

send

Use to send message between scripts. Can recognize the extension document context (background or content script). Requires tabId property when sending from background page.

Parameters

  • message Message A Message object with optional data properties.

Examples

message.send({
  greeting: 'hello',
  tabId: 1234, // Required if sending from background page.
})
  .then((response) => {
    console.log('They said:', response.greeting)
  })

Returns Promise<Message> Resolves if the other side responds.

sendFromTab

Send a message to the background script. See Chrome API. And MDN.

Parameters

  • message Message A Message object with optional data properties.

Examples

message.sendFromTab({ greeting: 'hello' })
  .then((response) => {
    console.log('They said', response.greeting)
  })

Returns Promise<Message> Resolves if the other side responds.

sendToTab

Send a message from the background script to a tab.

Parameters

  • message Message Must have a greeting and tabId property.

Examples

message.sendToTab({
  greeting: 'hello',
  tabId: 1234,
}).then((response) => {
  console.log('They said', response.greeting)
})

Returns Promise<Message> Resolves if the other side responds.

listenForMessage

Listen for messages from other tabs/pages.

The response Message object will be processed before it is sent:

  • If there is no error, message.success = true.
  • If there was an error, message.success = false and the error's message and stack will be assigned to the response object.
  • If response.greeting is undefined, the original greeting will be assigned.

Parameters

  • sendResponse boolean If true, will send a response. Defaults to true. (optional, default true)

Examples

message.listenForMessage()
  .forEach(({greeting}) => {
    console.log('They said', greeting)
  })

Returns BumbleStream Returns the BumbleStream object. The final return value of the stream will be sent as a message response.

notify

Wrapper for the chrome.notifications API. Use to create rich notifications using templates and show these notifications to users in the system tray.

See the Chrome API Docs and MDN.

NoteType

Referred to as "TemplateType" on Chrome API Docs.

  • basic: icon, title, message, expandedMessage, up to two buttons.
  • image: icon, title, message, expandedMessage, image, up to two buttons.
  • list: icon, title, message, items, up to two buttons. Users on Mac OS X only see the first items.
  • progress: icon, title, message, progress, up to two buttons.

See the Chrome API Docs.

Type: ("basic" | "image" | "list" | "progress")

NoteButton

Defines the notification action button.

Type: Object

Properties

NoteItem

Items for list notifications. Users on Mac OS X only see the first item.

Type: Object

Properties

  • title string Title of one item of a list notification.
  • message string Additional details about this item.

NoteOptions

Rich Notifications - Chrome Extensions API Docs

See the Chrome API Docs

Type: Object

Properties

  • type NoteType?
  • iconUrl string? A URL pointing to an icon to display in the notification. The URL can be: a data URL, a blob URL, a http or https URL, or the relative URL of a file within the extension.
  • title string? Title of the notification
  • message string? Main notification content
  • contextMessage string? Alternate notification content with a lower-weight font.
  • priority number? Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.
  • eventTime number? A timestamp for the notification in milliseconds
  • buttons Array<NoteButton>? Text and icons for up to two notification action buttons.
  • items Array<NoteItem>? Items for multi-item notifications. Users on Mac OS X only see the first item.
  • progress integer? An integer between 0 and 100, used to represent the current progress in a progress indicator.
  • requireInteraction boolean? Indicates that the notification should remain visible on screen until the user activates or dismisses the notification.
  • silent boolean? Indicates that no sounds or vibrations should be made when the notification is being shown. This defaults to false.

create

Creates a desktop notification. See the Chrome API Docs.

Parameters

  • details Object Details of the notification to create.
    • details.id string? Identifier of the notification. If not set or empty an ID will automatically be generated.
    • details.options ...NoteOptions? Contents of the notification.
      • details.options.type NoteType Which type of notification to display.
      • details.options.iconUrl string Which type of notification to display.
      • details.options.title string Title of the notification (e.g. Sender name for email).
      • details.options.message string Main notification content.

Examples

notify
  .create({
    type: NoteType.basic,
    message: 'Something to say',
    buttons: [{ title: 'Click here!' }],
    iconUrl: 'icon.png',
    id: item.asin,
  })

Returns Promise<{id: {string: string?}}> Resolves to an object with the notification id, as well as the original NotificationOptions properties.

pages

openOptionsPage

Opens the options page as defined in manifest.json. See Chrome API Docs and MDN.

Examples

options.open().then(() => {
  console.log('The options page is open.')
})

Returns Promise Resolves after the option page opens.

getBackgroundPage

Retrieves the Window object for the background page running inside the current extension. If the background page is unloaded, this will load the background page before resolving.

See Chrome API Docs and MDN.

Examples

getBackgroundPage().then((bgWindow) => {
  // The background page window.
})

Returns Promise<Window> A Promise that will be fulfilled with the Window object for the background page, if there is one.

proxy

Use the chrome.proxy API to manage Chrome's proxy settings. See Chrome API Docs

ProxyMode

A ProxyConfig object's mode attribute determines the overall behavior of Chrome with regards to proxy usage. See Chrome API Docs.

  • direct mode: all connections are created directly, without any proxy involved. This mode allows no further parameters in the ProxyConfig object.
  • auto_detect mode: the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat. This mode allows no further parameters in the ProxyConfig object.
  • pac_script mode: the proxy configuration is determined by a PAC script that is either retrieved from the URL specified in the proxy.PacScript object or taken literally from the data element specified in the proxy.PacScript object. Besides this, this mode allows no further parameters in the ProxyConfig object.
  • fixed_servers mode: the proxy configuration is codified in a proxy.ProxyRules object. Its structure is described in Proxy rules. Besides this, the fixed_servers mode allows no further parameters in the ProxyConfig object.
  • system mode: the proxy configuration is taken from the operating system. This mode allows no further parameters in the ProxyConfig object. Note that the system mode is different from setting no proxy configuration. In the latter case, Chrome falls back to the system settings only if no command-line options influence the proxy configuration.

Type: ("direct" | "auto_detect" | "pac_script" | "fixed_servers" | "system")

ProxyScheme

The connection to the proxy server uses the protocol defined in the scheme attribute. If no scheme is specified, the proxy connection defaults to http. See Chrome API Docs

  • http.
  • https.
  • quic.
  • socks4.
  • socks5.

Type: ("http" | "https" | "quic" | "socks4" | "socks5")

ProxyLevelOfControl

The level of control available to the extension for the proxy setting.

  • not_controllable
  • controlled_by_other_extensions
  • controllable_by_this_extension
  • controlled_by_this_extension

Type: ("not_controllable" | "controlled_by_other_extensions" | "controllable_by_this_extension" | "controlled_by_this_extension")

ProxyScope

Chrome distinguishes between three different scopes of browser settings. See Chrome API Docs

  • regular: settings set in the regular scope apply to regular browser windows and are inherited by incognito windows if they are not overwritten. These settings are stored to disk and remain in place until they are cleared by the governing extension, or the governing extension is disabled or uninstalled.
  • regular_only: settings set in the incognito_persistent scope apply only to incognito windows. For these, they override regular settings. These settings are stored to disk and remain in place until they are cleared by the governing extension, or the governing extension is disabled or uninstalled.
  • incognito_persistent: settings set in the incognito_session_only scope apply only to incognito windows. For these, they override regular and incognito_persistent settings. These settings are not stored to disk and are cleared when the last incognito window is closed. They can only be set when at least one incognito window is open.
  • incognito_session_only

Type: ("regular" | "regular_only" | "incognito_persistent" | "incognito_session_only")

ProxyServer

A proxy server is configured in a proxy.ProxyServer object. See Chrome API Docs

Type: Object

Properties

  • scheme ProxyScheme The scheme (protocol) of the proxy server itself. Defaults to 'http'.
  • host string The URI of the proxy server. This must be an ASCII hostname (in Punycode format).
  • port string The port of the proxy server. Defaults to a port that depends on the scheme.

ProxyRules

An object encapsulating the set of proxy rules for all protocols. Use either 'singleProxy' or (a subset of) 'proxyForHttp', 'proxyForHttps', 'proxyForFtp' and 'fallbackProxy'. See Chrome API Docs

Type: Object

Properties

  • singleProxy ProxyServer The proxy server to be used for all per-URL requests (that is http, https, and ftp).
  • mode Mode

ProxyConfig

An object encapsulating a complete proxy configuration. See Chrome API Docs

Type: Object

Properties

  • rules ProxyRules The proxy rules describing this configuration. Use this for 'fixed_servers' mode.
  • mode Mode

createProxyServer

Create a valid ProxyServer. Params will be type coerced and trimmed. The scheme will default to 'http' if none is specified. The port will be derived from the scheme if it is not defined. See Chrome API Docs.

Parameters

  • details Object Setting details
    • details.host string The proxy server host ip. Will trim any leading or trailing whitespace.
    • details.port number? The proxy server port.
    • details.scheme ProxyScheme? The proxy server scheme.

Examples

const server = createProxyServer({ host: '10.10.10.4' })

Returns ProxyServer Valid proxy server object.

createSingleProxyConfig

Create a valid ProxyConfig. See Chrome API Docs.

Parameters

Examples

const config = createSingleProxyConfig({host: '10.4.0.1'})

Returns ProxyConfig Returns an object encapsulating a complete proxy configuration.

ProxySettings

An object returned from proxy.get().

Type: Object

Properties

  • value ProxyConfig The current ProxyConfig.
  • levelOfControl ProxyLevelOfControl The level of extension control over proxy settings.
  • incognitoSpecific boolean Whether the effective value is specific to the incognito session. This property will only be present if the incognito property in the details parameter of proxy.get() was true.

get

Get the current proxy settings. See Chrome API Docs.

Parameters

  • details Object? Setting details
    • details.incognito boolean? Whether to return the value that applies to the incognito session (default false).

Examples

const proxySettingsPromise = proxy.get()

Returns Promise<ProxySettings> The value of the proxy settings.

set

Sets the current proxy settings. See Chrome API Docs.

Parameters

  • details Object Setting details
    • details.config ProxyConfig An object encapsulating a complete proxy configuration.
    • details.scope ProxyScope? One of the values from ProxyScope.

Examples

proxy.set({ config: ProxyConfig }).then(() => {
  console.log('Now using your proxy settings.')
})

Returns Promise Resolves at the completion of the set operation. Rejects if there was an error.

clear

Clears the current proxy settings and restores the default.

Parameters

  • details Object? Setting details
    • details.scope ProxyScope? One of the values from ProxyScope.

Examples

proxy.clear().then(() => {
  console.log('Now using a direct connection.')
})

Returns Promise Resolves after the default proxy settings have been restored. Rejects if there was an error.

storageLocal

This is a wrapper for the local Chrome extension storage API. Enables extensions to store and retrieve data, and listen for changes to stored items.

See the Chrome API Docs, and MDN storage.

set

Store one or more items in the storage area, or update existing items. When you store or update a value using this API, the onChanged event will fire.

See the Chrome API Docs and MDN.

Parameters

  • values Object An object containing one or more key/value pairs to be stored in storage. If an item already exists, its value will be updated.

Examples

// Save primitive values or Arrays to storage.
local.set({ email: 'sample@gmail.com' })
  .then(() => {
    console.log('The item "email" was set.')
  })
// Storage cannot save other types,
// such as Function, Date, RegExp, Set, Map, ArrayBuffer and so on.
local.set({ dogs: new Set(['Fluffy', 'Duke', 'Baby']) })
  .catch((error) => {
    console.log('There was a problem!')
  })

Returns Promise Resolves on success or rejects on failure.

get

Retrieves one or more items from the storage area.

See the Chrome API Docs and MDN.

Parameters

  • keys (string | Array<string>) A string or array of key names to retrieve from storage. If keys is undefined, returns all items in storage.

Examples

local.get('cats')
  .then(({cats}) => {
    console.log('Cats!', cats)
  })
local.get()
  .then((allItems) => {
    console.log('Every item in storage:', allItems)
  })
local.get(['cats', 'dogs'])
  .then(({cats, dogs}) => {
    console.log('Cats!', cats)
    console.log('Dogs!', dogs)
  })

Returns Promise<Object> Resolves with an object representing the values of the items or rejects on failure.

clear

Removes all items from the storage area.

See Chrome API Docs and MDN.

Examples

local.clear()
  .then(() => {
    console.log('Storage was cleared.')
  })

Returns Promise Resolves on success or rejects on failure.

remove

Removes one or more items from the storage area.

See the Chrome API Docs and MDN.

Parameters

  • keys (string | Array<string>) A string, or array of strings, representing the key(s) of the item(s) to be removed.

Examples

local.remove('key')
  .then(() => {
    console.log('The property "key" was removed.')
  })
local.remove(['key', 'lock'])
  .then(() => {
    console.log('The property "key" was removed.')
    console.log('The property "lock" was removed.')
  })

Returns Promise Resolves on success or rejects on failure.

storageSync

This is a wrapper for the local Chrome extension storage API. Enables extensions to store and retrieve data, and listen for changes to stored items.

See the Chrome API Docs, and MDN storage.

set

Store one or more items in the storage area, or update existing items. When you store or update a value using this API, the onChanged event will fire.

See the Chrome API Docs and MDN.

Parameters

  • values Object An object containing one or more key/value pairs to be stored in storage. If an item already exists, its value will be updated.

Examples

// Save primitive values or Arrays to storage.
sync.set({ email: 'sample@gmail.com' })
  .then(() => {
    console.log('The item "email" was set.')
  })
// Storage cannot save other types,
// such as Function, Date, RegExp, Set, Map, ArrayBuffer and so on.
sync.set({ dogs: new Set(['Fluffy', 'Duke', 'Baby']) })
  .catch((error) => {
    console.log('There was a problem!')
  })

Returns Promise Resolves on success or rejects on failure.

get

Retrieves one or more items from the storage area.

See the Chrome API Docs and MDN.

Parameters

  • keys (string | Array<string>) A string or array of key names to retrieve from storage.

Examples

sync.get('cats')
  .then(({cats}) => {
    console.log('Cats!', cats)
  })
sync.get(['cats', 'dogs'])
  .then(({cats, dogs}) => {
    console.log('Cats!', cats)
    console.log('Dogs!', dogs)
  })

Returns Promise<Object> Resolves with an object representing the values of the items or rejects on failure.

clear

Removes all items from the storage area.

See Chrome API Docs and MDN.

Examples

sync.clear()
  .then(() => {
    console.log('Storage was cleared.')
  })

Returns Promise Resolves on success or rejects on failure.

remove

Removes one or more items from the storage area.

See the Chrome API Docs and MDN.

Parameters

  • keys (string | Array<string>) A string, or array of strings, representing the key(s) of the item(s) to be removed.

Examples

sync.remove('key')
  .then(() => {
    console.log('The property "key" was removed.')
  })
sync.remove(['key', 'lock'])
  .then(() => {
    console.log('The property "key" was removed.')
    console.log('The property "lock" was removed.')
  })

Returns Promise Resolves on success or rejects on failure.

tabs

Wrapper for the chrome.tabs API. Use to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser.

See the Chrome API Docs and MDN.

Tab

See the Tab type in the Chrome API Docs.

The type tabs.Tab contains information about a tab. This provides access to information about what content is in the tab, how large the content is, what special states or restrictions are in effect, and so forth.

Type: Object

Properties

  • id integer?
  • index integer The zero-based index of the tab within its window.
  • windowId integer The ID of the window that contains the tab.
  • openerTabId integer? The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists.
  • highlighted boolean Whether the tab is highlighted.
  • active boolean Whether the tab is active in its window. Does not necessarily mean the window is focused.
  • pinned boolean Whether the tab is pinned.
  • audible boolean? Whether the tab has produced sound over the past couple of seconds (but it might not be heard if also muted). Equivalent to whether the 'speaker audio' indicator is showing.
  • discarded boolean Whether the tab is discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content is reloaded the next time it is activated.
  • autoDiscardable boolean Whether the tab can be discarded automatically by the browser when resources are low.
  • url string? The URL the tab is displaying.
  • title string? The title of the tab.
  • favIconUrl string? The URL of the tab's favicon. It may also be an empty string if the tab is loading.
  • status string? Either loading or complete
  • incognito boolean Whether the tab is in an incognito window.
  • width integer? The width of the tab in pixels.
  • height integer? The height of the tab in pixels.
  • sessionId string? The session ID used to uniquely identify a Tab obtained from the sessions API.

CreateProperties

See the Chrome API Docs

Type: Object

Properties

  • windowId integer? The window in which to create the new tab. Defaults to the current window.
  • index integer? The position the tab should take in the window. The provided value is clamped to between zero and the number of tabs in the window.
  • url string? The URL to initially navigate the tab to. Fully-qualified URLs must include a scheme (i.e., 'http://www.google.com', not 'www.google.com'). Relative URLs are relative to the current page within the extension. Defaults to the New Tab Page.
  • active boolean? Whether the tab should become the active tab in the window. Does not affect whether the window is focused (see windows.update). Defaults to true.
  • pinned boolean? Whether the tab should be pinned. Defaults to false
  • openerTabId integer? The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab.

create

Creates a new tab. See Chrome API Docs and MDN.

Parameters

  • details CreateProperties? An object with optional properties for the new tab.

Examples

tabs.create({
  url: 'http://www.google.com',
}).then((tab) => {
  console.log('The new tab id is:', tab.id)
})
tabs.create().then((tab) => {
  console.log('It is just a new active tab.')
})

Returns Tab The created tab.

get

Given a tab ID, get the tab's details as a tabs.Tab object. Without the "tabs" permission, will omit url, title, and favIconUrl.

See Chrome API Docs and MDN.

Parameters

  • details Object? The details of a tab.
    • details.tabId number? ID of the tab to get.

Examples

tabs.get({ tabId: 12345 })
  .then((tab) => {
    console.log(tab.status)
  })
tabs.get({ tabId: 12345 })
  .then((tab) => {
    // Requires "tabs" permission
    console.log(tab.title)
  })

Returns Promise<Tab> A Promise that will be fulfilled with a tabs.Tab object containing information about the tab.

query

Gets all tabs that have the specified properties, or all tabs if no properties are specified. Some queryInfo properties are ignored without the "tabs" permission.

See Chrome API Docs and MDN.

Parameters

Examples

tabs.query({
  active: true,
}).then((tabs) => {
  console.log('All the active:', tabs)
})
tabs.query({
  // The url property requires the 'tabs' permission.
  url: 'https://*.google.com/*',
}).then((tabs) => {
  console.log('All the Google tabs:', tabs)
})

Returns Promise<Array<Tab>> A Promise that will be fulfilled with an array of the queried tabs.Tab objects.

update

Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified. See Chrome API Docs and MDN.

Parameters

Examples

tabs.update({
  tabId: 12345,
  url: 'http://www.google.com',
}).then((tab) => {
  console.log('The tab was updated.')
})

Returns Promise<Tab> A Promise that will be fulfilled with a tabs.Tab object containing details about the updated tab.

close

Closes one or more tabs.

See the Chrome API Docs and MDN.

Parameters

Examples

tabs.close({ tabId: 12345 })
  .then(() => {
    console.log('The tab was closed.')
  })
tabs.close({ tabId: [12345, 67890] })
  .then(() => {
    console.log('Two tabs were closed.')
  })

Returns Promise Resolves on success or rejects on failure with the reason.

execute

Inject JavaScript code into a page. The script will execute in its own environment, but will share the DOM of the page. This requires either a host permission or the activeTab permission. Either the code or file property must be set in the details param.

See programmatic injection in the Chrome API Docs.

Parameters

Examples

tabs.execute({
  tabId: 12345,
  file: 'content-script.js',
}).then((tab) => {
  console.log('')
})

Returns Promise<Array> Resolves with an array of the results of the script in every injected frame.

0.1.1

5 years ago

0.1.0

5 years ago

0.0.1

5 years ago