extension-helpers
v2.0.1
Published
Promisified, cross-browser wrappers and helpers for extension APIs.
Downloads
7
Readme
Browser Extension Helpers
Work in progress, PRS welcome
import extensionHelpers from 'extension-helpers';
// or
const extensionHelpers = require('extension-helpers').default;
Promisified, cross-browser wrappers and helpers for extension APIs.
- Normalized & Promisified: no more fussing with Chrome's irregular callbacks, all functions returns a promise
- Simple: hide the
browser.api.action
boilerplate behind function calls - Cross-Browser: use the same functions on Chrome, Firefox, or Edge
Note: Many APIs are not supported in Edge. Check their documentation.
API
Table of Contents
- wallpaper
- alarms
- history
- extension
- localStorage
- message
- tabs
- windows
- notifications
- runtime
- cookie
- BadgeManager
- index
wallpaper
Manage wallpapers
set
CHROME ONLY. Sets wallpaper to an image (url) or Array buffer (data).
Parameters
filename
String File name of saved wallpaperlayout
WallpaperLayout A WallpaperLayout Enum valueparams
Object? Optional thumbnail, binary image source and url. See Chrome API docs for options(https://developer.chrome.com/extensions/wallpaper)
alarms
Schedule code to run at a specific time.
create
- See: Firefox Alarms or Chrome Alarms
Creates a new alarm.
Parameters
name
String? Optional name to identify alarm.optionalParams
Object? Object of shape { when: {Number}, delayInMinutes: {Number}, periodInMinutes: {Number} }. Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes.
Returns Promise<undefined> Promise resolved with undefined or rejected with an error.
get
Gets an alarm, given its name.
Parameters
name
String? Optional. The name of the alarm to get. Defaults to the empty string.
Returns Promise<Alarm> A Promise resolved with an Alarm object or rejected with an error. If resolved, value represents the alarm whose name matches name. If no alarms match, this will be undefined.
getAll
Gets all active alarms for the extension.
Returns Promise<Array<Alarm>> Promise resolved with an array of Alarm objects or rejected with an error. Resolves with empty array if no alarms are active.
clear
Clears the alarm with the given name.
Parameters
name
String Name of the alarm to cancel. Default is empty string.
Returns Promise<Boolean> Promise resolved with true if alarm was cleared or false if not cleared, or rejected with an error.
clearAll
- See: MDN on clearAll
Cancels all active alarms.
Returns Promise<Boolean> Promise resolved with true if any alarms were cleared or false otherwise. Or, rejected with an error.
history
Search and manage browser history
search
Search the browser history for last visit time of each page matching the query
Parameters
text
String A free-text query to the history service. Leave empty to retrieve all pages.optionalStartTime
Number Double. Limit results to those visited after this date, represented in milliseconds since the epoch. If not specified, this defaults to 24 hours in the past.optionalEndTime
Number Double. Limit results to those visited before this date, represented in milliseconds since the epoch.optionalMaxResults
Number Integer. The maximum number of results to retrieve. Defaults to 100.
Returns Promise<Array<HistoryItem>> Promise that resolves with array of HistoryItem objects or rejects with error
getVisits
Gets information about visits to a url
Parameters
url
String Must be fully qualified url including protocol
Returns Promise<Array<VisitItem>> Promise that resolves with array of VisitItems or rejects with an error
addUrl
Chrome: Adds a URL to the history at the current time with a transition type of "link". Firefox: Adds a record to the browser's history of a visit to the given URL. The visit's time is recorded as the time of the call, and the TransitionType is recorded as "link".
Parameters
url
String The URL to addoptionalParams
Object Firefox only. Object with shape { title: {String}, transition: {TransitionType}, visitTime: {Number | String | Object} }. All optional.
Returns Promise<undefined> Promise resolved with undefined or rejected with an error.
deleteUrl
Removes all visits to the given URL from the browser history.
Parameters
url
String The URL whose visits should be removed.
Returns Promise<undefined> Promise resolved with undefined or rejected with an error;
deleteRange
Removes all items within the specified date range from the history. Pages will not be removed from the history unless all visits fall within the range.
Parameters
startTime
(Number | String | Date) Items added to history after this date, represented in milliseconds since the epoch.endTime
(Number | String | Date) Items added to history before this date, represented in milliseconds since the epoch.
Returns Promise<undefined> Promise resolved with undefined or rejected with an error.
deleteAll
Deletes all items from the history.
Returns Promise<undefined> Promise resolved with undefined or rejected with an error.
extension
Enable, disable, and manage other browser extensions
self
Get information about the calling extension
Returns Promise<ExtensionInfo> Object with info about the extension
permissionWarningsById
Get a list of permission warnings for the given extension id
Parameters
id
String The browser-assigned id of the extension
Returns Promise<Array<String>> Promised resolved with array of permission warnings or rejected with error
permissionWarningsByManifest
Get a list of permission warnings for the given extension manifest string
Parameters
manifestStr
String Extension manifest JSON string.
Returns Promise<Array<String>> Promised resolved with array of permission warnings or rejected with error
enable
Enable (activate) a browser extension
Parameters
id
String The browser-assigned id of the extension
Returns Promise<Boolean> Promise resolved with true if successful or rejected with error
disable
Disable (deactivate) a browser extension
Parameters
id
String The Browser-assigned id of the extension
Returns Promise<Boolean> Promise resolved with false if successful or rejected with error
getAll
Get all currently installed browser extension
Returns Promise<Array<ExtensionInfo>> Promise resolved with array of browser extension information objects, or rejected with error
get
Get a browser by extension id
Parameters
id
String Browser-assigned extension id
Returns Promise<ExtensionInfo> Promise resolved with browser extension information object or rejected with an error
localStorage
Manage the local storage of your browser extension
set
Set a value at a given key in the extension's local storage
Parameters
key
String Key for the set valuevalue
Any Value to serialize to local storage. Objects and functions serialized to {}. Arrays, Regex, and primitives serialize correctly.
Returns Promise<undefined> Promise resolved with nothing, or rejected with error
get
Get the value for a given key in local storage
Parameters
key
(String | Array<String> | null) Single key to get, array of keys to get, or null to get entire contents
Returns Promise<Object> Promise resolved with object with key-value mappings or rejected with an error
message
Send messages to tabs
tab
Send a message directly to tab by id
Parameters
Returns Promise<Object> Promise resolved with response or rejected with error
allTabs
Sends a message to all tabs in any window
Parameters
message
Object Any valid JSON-ifiable object
Returns Promise<Array<Tab>> Promise resolved with array of responses from tabs that were sent a message or rejected with an error
activeTabs
Sends a message to tabs that are considered 'active' (focused) for all open browser windows
Parameters
message
Object Any valid JSON-ifiable object
Returns Promise<Array<Tab>> Promise resolved with array of responses from tabs that were sent a message rejected with an error
manyTabs
Send a message to an array of tabs
Parameters
tabArr
Array<Tab> Array of Tab objects to send message tomessage
Object Any valid JSON-ifiable object
Returns Promise<Array<Object>> Promise resolved with array of responses from messages or rejected with an error
activeTab
Send message to active (focused) tab in the current window.
Parameters
message
Object Any valid JSON-ifiable object
Returns Promise<Object> Promise resolved with response from tab or rejected with an error
tabs
Open, close, focus, blur and manage tabs.
focus
Forces browser focus on given tab
Parameters
Returns Promise<Object> resolved with tabDetails object or rejected with error
close
Closes a tab by tab id
Parameters
tabIds
number an array
Returns Promise<undefined> Promise resolved with undefined or rejected with error
getActive
Gets currently active tab (the tab focused in current browser window)
Returns Promise<Object> tab object
executeOnActive
Execute a file or code on a given tab
Parameters
toInject
String file name or raw code to executetypeToInject
String valid params are "code" or "file"
Returns Promise<Object> any results of the injected code's execution
open
Open a new tab optionally blurred or focused, and return the new tab's id.
Parameters
Returns Promise<Object> resolved with the newly opened tab or rejected with error
getAllActive
Get active tabs in all browser windows
Returns Promise<Array<Object>> Promise resolved with an array of all active tab objects or rejected with an error
getAll
Get all tabs
Returns Promise<Array<Object>> Promise resolved with all tabs or rejected with an error
executeOnAll
Execute raw js or a script by filename on all tabs
Parameters
toInject
String file name or raw code to executetypeToInject
String valid params are "code" or "file"
Returns Array<Promise<Object>> Array Promises resolved with any results of the injected code's execution or rejected with an error
executeOnAllActive
Executes a file or inline code as a string on all the active tabs of all windows.
Parameters
toInject
String file name or raw code to executetypeToInject
String valid params are "code" or "file"
Returns Array<Promise<Object>> Array of Promises resolved with any results of the injected code's execution or rejected with an error
getCurrent
Get tab that the script call is being made from
Returns Promise<Tab> Promise that resolves with Tab or rejects with error
reload
Reloads a tab by id. Optionally bypasses cache.
Parameters
Returns Promise<undefined> Bypass
windows
Manage browser windows
getById
- See: Chrome filter defaults for this API
- See: Firefox filter defaults for this API
Get a window by id
Parameters
windowId
Number Integer Id of windowincludeTabs
Boolean? Include array of window's associated Tab objects. Default false.filterWindowTypes
Array<WindowTypes>? Array to filter window by WindowType. Chrome and Firefox support different WindowTypes.
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
getCurrent
Get the current browser window
Parameters
includeTabs
Boolean? Include array of window's associated Tab objects. Default false.filterWindowTypes
Array<WindowTypes>? Array to filter window by WindowType. Chrome and Firefox support different WindowTypes.
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
getLastFocused
Get the most recently focused window. Usually the window 'on top'.
Parameters
includeTabs
Boolean? Include array of window's associated Tab objects. Default false.filterWindowTypes
Array<WindowTypes>? Array to filter window by WindowType. Chrome and Firefox support different WindowTypes.
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
getAll
Get all open windows
Parameters
includeTabs
Boolean? Include array of window's associated Tab objects. Default false.filterWindowTypes
Array<WindowTypes>? Array to filter window by WindowType. Chrome and Firefox support different WindowTypes.
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
create
Opens a new browser window with optional parameters.
Parameters
url
String? Fully qualified url to open in new windowparams
Object Optional parameters like incognito, focused, positioning, and tabid. See Chrome and Firefox docs for complete list.
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
update
Update a Window's state
Parameters
windowId
Number Integer Id of window to updateparams
Object? Optional parameters like height, width, and state.
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
focus
Focus on a given window
Parameters
windowId
Number Integer Id of window to focus
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
drawAttention
Draw attention to a given window
Parameters
windowId
Number Integer Id of window to focus
Returns Promise<Window> Promise resolved with a Window object or rejected with an error.
notifications
Send and manage browser notifications
create
- See: NotificationsOptions
Create and display a new notification
Parameters
notificationId
String? optional id to assign notification. If empty will be automatically generatedoptions
Object NotificationsOptions object
Returns Prromise<String> id of created notification
update
- See: NotificationsOptions
Update existing notification
Parameters
Returns Promise<Boolean> Boolean wasUpdated indicating whether notification was updated
clear
- See: NotificationsOptions
Clear specified notification
Parameters
notificationId
String id of notification to clear
Returns Promise<Boolean> Boolean wasCleared specifying whether the matching notification existed
getAll
Get all notifications
runtime
Manage runtime tasks like messaging extensions
sendMessage
Sends a message to an extension identified by its id
Parameters
extensionId
String? optional extension idmsg
String Any JSON-ifiable objectoptions
[type] options (optional, default{}
)
Returns Promise<Object> Promise resolved with response from tab or rejected with an error
cookie
Manage cookies in the browser
get
- See: How Chrome handles cookies with the same name
Get a cookie by name for a given url.
Parameters
url
String URL of site to get cookie fromname
String Name of cookie to getstoreId
String? The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store will be used.
Returns Promise<Cookie> Promise resolved with Cookie object or rejected with error
set
- See: How Chrome handles cookies with the same name
Set a cookie by name for a given url.
Parameters
url
String URL of site to get cookie fromname
String Name of cookie to getvalue
String Value of cookieoptionalParamsObj
Object? See Chrome docs for details of this object
Returns Promise<Cookie> Promise resolved with Cookie object or rejected with error
getAll
Get all cookies by name for a given url
Parameters
url
String? Optional url to get cookies fromname
String? Optional name of cookie to get from urloptionalParamsObj
Object? Optional parameters, see Chrome docs for specifics of other params
Returns Promise<Array<Cookie>> Promise resolved with array of Cookie objects or rejected with an error
remove
Remove a cookie by name for a given url
Parameters
url
String URL of site to remove cookie fromname
String Name of cookie to removestoreId
String? The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store will be used.
Returns Promise<Object> Promise resolved with details of cookie that has been removed or rejected with error
getAllCookieStores
Lists all existing cookie stores.
Returns Promise<Array<CookieStore>> Promise resolved with an array of CookieStore objects or rejected with an error.
BadgeManager
A BadgeManager object for controlling the badges on your extension's Browser Action toolbar icon. Should be used as a singleton, since it tracks the state of your extension's badges.
Parameters
badgeColor
String The hex code of the color for your badge
add
Add a number to your badge's current value
Parameters
num
Number The number to add to your badge
Returns undefined nothing
subtract
Subtract a number from your badge's current value
Parameters
num
Number The number to subtract
Returns undefined nothing
clear
Clear your badge
Returns undefined nothing
index
Retrieves whether the user has enabled notifications from the app/extension
Something broken?
Go bother: