@bumble/chrome v0.1.1
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
detailsObject 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
detailsObject Badge text options.
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
detailsObject Badge text options.
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
detailsObject? Title text options.
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
detailsObject 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
greetingstring A constant to identify the message type.tabIdnumber? 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
messageMessage 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
messageMessage 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
messageMessage 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 = falseand the error's message and stack will be assigned to the response object. - If
response.greetingisundefined, the original greeting will be assigned.
Parameters
sendResponseboolean If true, will send a response. Defaults to true. (optional, defaulttrue)
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
titlestring Title of one item of a list notification.messagestring Additional details about this item.
NoteOptions
Rich Notifications - Chrome Extensions API Docs
See the Chrome API Docs
Type: Object
Properties
typeNoteType?iconUrlstring? 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.titlestring? Title of the notificationmessagestring? Main notification contentcontextMessagestring? Alternate notification content with a lower-weight font.prioritynumber? Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.eventTimenumber? A timestamp for the notification in millisecondsbuttonsArray<NoteButton>? Text and icons for up to two notification action buttons.itemsArray<NoteItem>? Items for multi-item notifications. Users on Mac OS X only see the first item.progressinteger? An integer between 0 and 100, used to represent the current progress in a progress indicator.requireInteractionboolean? Indicates that the notification should remain visible on screen until the user activates or dismisses the notification.silentboolean? 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
detailsObject Details of the notification to create.details.idstring? Identifier of the notification. If not set or empty an ID will automatically be generated.details.options...NoteOptions? Contents of the notification.
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.
directmode: all connections are created directly, without any proxy involved. This mode allows no further parameters in the ProxyConfig object.auto_detectmode: 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_scriptmode: 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_serversmode: 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.systemmode: 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_controllablecontrolled_by_other_extensionscontrollable_by_this_extensioncontrolled_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
schemeProxyScheme The scheme (protocol) of the proxy server itself. Defaults to 'http'.hoststring The URI of the proxy server. This must be an ASCII hostname (in Punycode format).portstring 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
singleProxyProxyServer The proxy server to be used for all per-URL requests (that is http, https, and ftp).modeMode
ProxyConfig
An object encapsulating a complete proxy configuration. See Chrome API Docs
Type: Object
Properties
rulesProxyRules The proxy rules describing this configuration. Use this for 'fixed_servers' mode.modeMode
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
detailsObject Setting details
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
detailsObject Setting detailsdetails.hoststring The proxy server host ip.details.portnumber? The proxy server port.details.bypassListArray<string>? List of websites to connect to without a proxy. See the bypassList docs.
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
valueProxyConfig The current ProxyConfig.levelOfControlProxyLevelOfControl The level of extension control over proxy settings.incognitoSpecificboolean 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
detailsObject? Setting detailsdetails.incognitoboolean? 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
detailsObject Setting detailsdetails.configProxyConfig An object encapsulating a complete proxy configuration.details.scopeProxyScope? 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
detailsObject? Setting detailsdetails.scopeProxyScope? 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
valuesObject 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
valuesObject 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
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
idinteger?indexinteger The zero-based index of the tab within its window.windowIdinteger The ID of the window that contains the tab.openerTabIdinteger? The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists.highlightedboolean Whether the tab is highlighted.activeboolean Whether the tab is active in its window. Does not necessarily mean the window is focused.pinnedboolean Whether the tab is pinned.audibleboolean? 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.discardedboolean 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.autoDiscardableboolean Whether the tab can be discarded automatically by the browser when resources are low.urlstring? The URL the tab is displaying.titlestring? The title of the tab.favIconUrlstring? The URL of the tab's favicon. It may also be an empty string if the tab is loading.statusstring? Either loading or completeincognitoboolean Whether the tab is in an incognito window.widthinteger? The width of the tab in pixels.heightinteger? The height of the tab in pixels.sessionIdstring? The session ID used to uniquely identify a Tab obtained from the sessions API.
CreateProperties
See the Chrome API Docs
Type: Object
Properties
windowIdinteger? The window in which to create the new tab. Defaults to the current window.indexinteger? 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.urlstring? 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.activeboolean? 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.pinnedboolean? Whether the tab should be pinned. Defaults to falseopenerTabIdinteger? 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
detailsCreateProperties? 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
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
queryInfoObject? Specified properties of tabs. See Chrome queryInfo.
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
detailsObject? The details of a tab.details.tabIdnumber? Defaults to the selected tab of the current window.details.updatePropsObject? Specified properties of tabs. See Chrome updateProperties.
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
detailsObject The details of a tab.
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
detailsObject? The details of a tab.details.tabIdnumber? The id of the tab to inject. Defaults to the active tab.details.codestring? JavaScript or CSS code to inject.details.filestring? The path to the JavaScript or CSS file to inject.details.detailsstring? Other optional details of the script to run..
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.