recursal/MDN huggingface dataset:
sessions.setTabValue()
======================

Stores a key/value pair to associate with a given tab. You can subsequently retrieve this value using `sessions.getTabValue`.

Note that this data will only be visible to the extension that set it, and not to any other extensions.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let storing = browser.sessions.setTabValue(
  tabId,    // integer
  key,      // string
  value     // string or object
)
```

### Parameters

`tabId`

`integer`. ID of the tab with which you want to associate the data. Error is thrown if ID is invalid.

`key`

`string`. Key that you can later use to retrieve this particular data value.

`value`

`string` or `object`. If this is an object it is stringified, so object methods, for example, will be omitted. If a function is given here it will be stored as the value `null`.

### Return value

A `Promise` that will be resolved with no arguments if the call succeeded. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Examples
--------

Set a value on the active tab when the user selects a menu item. Note that you'll need the "menus" permission to run this example:


```js
async function setOnActiveTab() {
  let tabArray = await browser.tabs.query({
    currentWindow: true,
    active: true,
  });
  let tabId = tabArray[0].id;
  await browser.sessions.setTabValue(tabId, "my-key", "my-value");
}

browser.menus.create({
  id: "my-item",
  title: "my item",
  contexts: ["all"],
});

browser.menus.onClicked.addListener(setOnActiveTab);
```

### Example extensions

* session-state
sessions.forgetClosedWindow()
=============================

Removes a closed window from the browser's list of recently closed windows. Note that the sites visited by that window are not removed from the browser's history. Use the `browsingData` or `history` APIs to remove history.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let forgettingWindow = browser.sessions.forgetClosedWindow(
  sessionId            // string
)
```

### Parameters

`sessionId`

`String`. The ID of the session you want to forget.

### Return value

A `Promise`. This will be fulfilled with no arguments when the session has been removed.

If an error occurs, the promise will be rejected with an error message.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Examples
--------

This code forgets the single most recently-closed session, whether it's a tab or a window:


```js
function forgetMostRecent(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.forgetClosedTab(
      sessionInfo.tab.windowId,
      sessionInfo.tab.sessionId,
    );
  } else {
    browser.sessions.forgetClosedWindow(sessionInfo.window.sessionId);
  }
}

function onError(error) {
  console.log(error);
}

browser.sessions
  .getRecentlyClosed({ maxResults: 1 })
  .then(forgetMostRecent, onError);
```
sessions.forgetClosedTab()
==========================

Removes a closed tab from the browser's list of recently closed tabs. Note that the sites visited by that tab are not removed from the browser's history. Use the `browsingData` or `history` APIs to remove history.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let forgettingTab = browser.sessions.forgetClosedTab(
  windowId,            // integer
  sessionId            // string
)
```

### Parameters

`windowId`

`Integer`. The ID of the window that hosted the tab you want to forget.

`sessionId`

`String`. The ID of the session you want to forget.

### Return value

A `Promise`. This will be fulfilled with no arguments when the session has been removed.

If an error occurs, the promise will be rejected with an error message.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Examples
--------

This code forgets the single most recently-closed session, whether it's a tab or a window:


```js
function forgetMostRecent(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.forgetClosedTab(
      sessionInfo.tab.windowId,
      sessionInfo.tab.sessionId,
    );
  } else {
    browser.sessions.forgetClosedWindow(sessionInfo.window.sessionId);
  }
}

function onError(error) {
  console.log(error);
}

browser.sessions
  .getRecentlyClosed({ maxResults: 1 })
  .then(forgetMostRecent, onError);
```
sessions.setWindowValue()
=========================

Stores a key/value pair to associate with a given window. You can subsequently retrieve this value using `sessions.getWindowValue`.

Note that this data will only be visible to the extension that set it, and not to any other extensions.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let storing = browser.sessions.setWindowValue(
  windowId,    // integer
  key,         // string
  value        // string or object
)
```

### Parameters

`windowId`

`integer`. ID of the window with which you want to associate the data. Error is thrown if ID is invalid.

`key`

`string`. Key that you can later use to retrieve this particular data value.

`value`

`string` or `object`. If this is an object it is stringified, so object methods, for example, will be omitted. If a function is given here it will be stored as the value `null`.

### Return value

A `Promise` that will be resolved with no arguments if the call succeeded. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Examples
--------

Set a value on the active window when the user selects a menu item. Note that you'll need the "menus" permission to run this example:


```js
async function setOnActiveWindow() {
  let currentWindow = await browser.windows.getLastFocused();
  await browser.sessions.setWindowValue(currentWindow.id, "my-key", "my-value");
}

browser.menus.create({
  id: "my-item",
  title: "my item",
  contexts: ["all"],
});

browser.menus.onClicked.addListener(setOnActiveWindow);
```
sessions.onChanged
==================

Fired whenever the list of closed tabs or windows changes.

Syntax
------


```js
browser.sessions.onChanged.addListener(listener)
browser.sessions.onChanged.removeListener(listener)
browser.sessions.onChanged.hasListener(listener)
```


Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

Stop listening to this event. The `listener` argument is the listener to remove.

`hasListener(listener)`

Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.

addListener syntax
------------------

### Parameters

`listener`

The function called when this event occurs. It's passed no parameters.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Examples
--------

This very annoying extension listens for `onChanged`, then immediately restores the most recently closed session, thus making it impossible to close windows or tabs:


```js
function restoreSession(sessionInfos) {
  if (!sessionInfos.length) {
    console.log("No sessions found");
    return;
  }
  let sessionInfo = sessionInfos[0];
  if (sessionInfo.tab) {
    browser.sessions.restore(sessionInfo.tab.sessionId);
  } else {
    browser.sessions.restore(sessionInfo.window.sessionId);
  }
}

function onError(error) {
  console.log(error);
}

function restoreMostRecent() {
  let gettingSessions = browser.sessions.getRecentlyClosed({
    maxResults: 1,
  });
  gettingSessions.then(restoreSession, onError);
}

browser.sessions.onChanged.addListener(restoreMostRecent);
```


**Note:** This API is based on Chromium's `chrome.sessions` API.
sessions.removeWindowValue()
============================

Removes a value previously stored by a call to `sessions.setWindowValue`.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let removing = browser.sessions.removeWindowValue(
  windowId,    // integer
  key          // string
)
```

### Parameters

`windowId`

`integer`. ID of the window whose data you are trying to remove. Error is thrown if ID is invalid.

`key`

`string`. Key identifying the particular value to remove. This needs to match the key previously given in `sessions.setWindowValue`.

### Return value

A `Promise` that will be resolved no arguments if the item was successfully removed. If the call failed (for example, because the window ID could not be found) then the promise will be rejected with an error message.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Examples
--------

This code adds two context menu items: one stores a value associated with the current window, the other one removes it:


```js
async function setOnActiveWindow() {
  let currentWindow = await browser.windows.getLastFocused();
  await browser.sessions.setWindowValue(currentWindow.id, "my-key", "my-value");
}

async function removeFromActiveWindow() {
  let currentWindow = await browser.windows.getLastFocused();
  await browser.sessions.removeWindowValue(currentWindow.id, "my-key");
}

browser.menus.create({
  id: "add-my-item",
  title: "add item",
  contexts: ["all"],
});

browser.menus.create({
  id: "remove-my-item",
  title: "remove item",
  contexts: ["all"],
});

browser.menus.onClicked.addListener((info) => {
  if (info.menuItemId === "add-my-item") {
    setOnActiveWindow();
  } else {
    removeFromActiveWindow();
  }
});
```
sessions.getTabValue()
======================

Retrieves a value previously stored by a call to `sessions.setTabValue`.

You can retrieve a value from a tab even over a close/restore cycle: meaning that if you set a value, then the user closes the tab, then restores the tab using the browser's "restore tab" feature (for example, by pressing Control+Shift+T), then you will be able to retrieve the value from the restored tab. Note, though, that a restored tab does not get the same ID as the original, so the ID you pass into `getTabValue()` will be different from the ID you passed into `setTabValue()`, even though they both refer to the same tab.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let retrieving = browser.sessions.getTabValue(
  tabId,    // integer
  key       // string
)
```

### Parameters

`tabId`

`integer`. ID of the tab whose data you are trying to retrieve. Error is thrown if ID is invalid.

`key`

`string`. Key identifying the particular value to retrieve. This needs to match the key previously given in `sessions.setTabValue`.

### Return value

A `Promise` that will be resolved with the value if it exists, or `undefined` if it does not exist. If the call failed (for example, because the tab ID could not be found) then the promise will be rejected with an error message.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Examples
--------

Log the value of "my-key" for all newly created tabs (this will include any tabs that have been restored):


```js
function onGetResolved(r) {
  console.log(`success: ${r}`);
}

function onGetRejected(e) {
  console.log(`error: ${e}`);
}

browser.tabs.onCreated.addListener((tab) => {
  browser.sessions
    .getTabValue(tab.id, "my-key")
    .then(onGetResolved, onGetRejected);
});
```

### Example extensions

* session-state
alarms.get()
============

Gets an alarm, given its name.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let getAlarm = browser.alarms.get(
  name                   // optional string
)
```

### Parameters

`name` Optional

`string`. The name of the alarm to get. If you don't supply this, the empty string "" will be used.

### Return value

A `Promise` that will be fulfilled with an ``Alarm`` object. This represents the alarm whose name matches `name`. If no alarms match, this will be `undefined`.

Examples
--------


```js
function gotAlarm(alarm) {
  if (alarm) {
    console.log(alarm.name);
  }
}

let getAlarm = browser.alarms.get("my-periodic-alarm");
getAlarm.then(gotAlarm);
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.
alarms.clearAll()
=================

Cancels all active alarms.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let clearAlarms = browser.alarms.clearAll()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with a boolean. This will be `true` if any alarms were cleared, `false` otherwise. Note that Chrome always passes `true` here.

Examples
--------


```js
function onClearedAll(wasCleared) {
  console.log(wasCleared); // true/false
}

let clearAlarms = browser.alarms.clearAll();
clearAlarms.then(onClearedAll);
```

### Example extensions

* chill-out
Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.
alarms.create()
===============

Creates a new alarm for the current browser session. An alarm may fire once or multiple times. An alarm is cleared after it fires for the last time.

Syntax
------


```js
browser.alarms.create(
  name,              // optional string
  alarmInfo          // optional object
)
```

### Parameters

`name` Optional

`string`. A name for the alarm. Defaults to the empty string.

This can be used to refer to a particular alarm in `alarms.get()` and `alarms.clear()`. It will also be available in `alarms.onAlarm` as the `name` property of the `alarms.Alarm` object passed into the listener function.

Alarm names are unique within the scope of a single extension. If an alarm with an identical name exists, the existing alarm will be cleared and the alarm being created will replace it.

`alarmInfo` Optional

`object`. You can use this to specify when the alarm will initially fire, either as an absolute value (`when`), or as a delay from the time the alarm is set (`delayInMinutes`). To make the alarm recur, specify `periodInMinutes`.

On Chrome, unless the extension is loaded unpackaged, alarms it creates are not allowed to fire more than once per minute. If an extension tries to set `delayInMinutes` to a value < 1, or `when` to a value < 1 minute in the future, then the alarm will fire after 1 minute. If an extension tries to set `periodInMinutes` to a value < 1, then the alarm will fire every minute.

The `alarmInfo` object may contain the following properties:

`when` Optional

`double`. The time the alarm will fire first, given as milliseconds since the epoch. To get the number of milliseconds between the epoch and the current time, use `Date.now()`. If you specify `when`, don't specify `delayInMinutes`.

`delayInMinutes` Optional

`double`. The time the alarm will fire first, given as minutes from the time the alarm is set. If you specify `delayInMinutes`, don't specify `when`.

`periodInMinutes` Optional

`double`. If this is specified, the alarm will fire again every `periodInMinutes` after its initial firing. If you specify this value you may omit both `when` and `delayInMinutes`, and the alarm will then fire initially after `periodInMinutes`. If `periodInMinutes` is not specified, the alarm will only fire once.


Examples
--------

Create a one-time delay-based alarm with "" for the name:


```js
const delayInMinutes = 5;

browser.alarms.create({
  delayInMinutes,
});
```


Create a periodic delay-based alarm named "my-periodic-alarm":


```js
const delayInMinutes = 5;
const periodInMinutes = 2;

browser.alarms.create("my-periodic-alarm", {
  delayInMinutes,
  periodInMinutes,
});
```


Create a periodic absolute alarm named "my-periodic-alarm":


```js
const when = 1545696000;
const periodInMinutes = 2;

browser.alarms.create("my-periodic-alarm", {
  when,
  periodInMinutes,
});
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.
alarms.clear()
==============

Cancels an alarm, given its name.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let clearAlarm = browser.alarms.clear(
  name                       // string
)
```

### Parameters

`name` Optional

`string`. The name of the alarm to clear. If you don't supply this, the empty string "" will be used.

### Return value

A `Promise` that will be fulfilled with a boolean. This will be `true` if the alarm was cleared, `false` otherwise.

Examples
--------


```js
function onCleared(wasCleared) {
  console.log(wasCleared); // true/false
}

let clearAlarm = browser.alarms.clear("my-periodic-alarm");
clearAlarm.then(onCleared);
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.
alarms.getAll()
===============

Gets all active alarms for the extension.

This is an asynchronous function that returns a `Promise`.

Syntax
------


```js
let getAlarms = browser.alarms.getAll()
```

### Parameters

None.

### Return value

A `Promise` that will be fulfilled with an array of `Alarm` objects. Each of these represents an active alarm that belongs to the extension. If no alarms are active, the array will be empty.

Examples
--------


```js
function gotAll(alarms) {
  for (const alarm of alarms) {
    console.log(alarm.name);
  }
}

browser.alarms.getAll().then(gotAll);
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.
alarms.onAlarm
==============

Fired when any alarm set by the extension goes off.

Syntax
------


```js
browser.alarms.onAlarm.addListener(listener)
browser.alarms.onAlarm.removeListener(listener)
browser.alarms.onAlarm.hasListener(listener)
```


Events have three functions:

`addListener(listener)`

Adds a listener to this event.

`removeListener(listener)`

Stop listening to this event. The `listener` argument is the listener to remove.

`hasListener(listener)`

Check whether `listener` is registered for this event. Returns `true` if it is listening, `false` otherwise.

addListener syntax
------------------

### Parameters

`listener`

The function called when this event occurs. The function is passed this argument:

`alarm`

`alarms.Alarm`. The alarm that fired. Use `Alarm.name` to figure out which alarm fired.


Examples
--------

Handle an alarm going off:


```js
function handleAlarm(alarmInfo) {
  console.log(`on alarm: ${alarmInfo.name}`);
}

browser.alarms.onAlarm.addListener(handleAlarm);
```

### Example extensions

* chill-out
* dynamic-theme
Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.
alarms.Alarm
============

Information about a single alarm. This object is returned from `alarms.get()` and `alarms.getAll()`, and is passed into the `alarms.onAlarm` listener.

Type
----

Values of this type are objects. They contain the following properties:

`name`

`string`. Name of this alarm. This is the name that was passed into the `alarms.create()` call that created this alarm.

`scheduledTime`

`double`. Time at which the alarm is scheduled to fire next, in milliseconds since the epoch.

`periodInMinutes` Optional

`double`. If this is not `null`, then the alarm is periodic, and this represents its period in minutes.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.alarms` API.
events.Event
============

An object which allows the addition and removal of listeners for a browser event.

Type
----

Values of this type are objects.

Methods
-------

`events.Event.addListener()`

Registers an event listener to an event.

`events.Event.removeListener()`

Deregisters an event listener from an event.

`events.Event.hasListener()`

Tests registration status of a listener.

`events.Event.hasListeners()`

Tests whether any listeners are registered to the event.

`events.Event.addRules()`

Registers rules to handle events.

`events.Event.getRules()`

Returns currently registered rules.

`events.Event.removeRules()`

Unregisters currently registered rules.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.events` API. This documentation is derived from `events.json` in the Chromium code.
events.Rule
===========

Description of a declarative rule for handling events.

Type
----

Values of this type are objects. They contain the following properties:

`id` Optional

`string`. Optional identifier that allows referencing this rule.

`tags` Optional

`array` of `string`. Tags can be used to annotate rules and perform operations on sets of rules.

`conditions`

`array` of `any`. List of conditions that can trigger the actions.

`actions`

`array` of `any`. List of actions that are triggered if one of the conditions is fulfilled.

`priority` Optional

`integer`. Optional priority of this rule. Defaults to 100.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** This API is based on Chromium's `chrome.events` API. This documentation is derived from `events.json` in the Chromium code.