Skip to content

Commit

Permalink
Add sharedstorage class
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisdavidmills committed Jul 19, 2023
1 parent 09f74e0 commit 7a1984e
Show file tree
Hide file tree
Showing 9 changed files with 360 additions and 10 deletions.
18 changes: 9 additions & 9 deletions files/en-us/web/api/shared_storage_api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ The [Private Aggregation API](https://developer.chrome.com/docs/privacy-sandbox/
- [**User demographic reporting**](https://developer.chrome.com/docs/privacy-sandbox/shared-storage/user-demographics/): Content producers often want to understand the demographics of their audience. You can use shared storage to record user demographic data on your main site, and use aggregated reporting to report on it across other sites, in embedded contexts.
- [**K+ frequency measurement**](https://developer.chrome.com/docs/privacy-sandbox/shared-storage/k-freq-reach/): Sometimes described as "effective frequency", K frequency refers to the minimum number of views before a user will recognize or recall certain content (often used in the context of ad views). You can use shared storage to build reports of unique users that have seen a piece of content at least K times.

## How does Shared Storage work?
## How does shared storage work?

There are two parts to using the Shared Storage API — writing data to storage, and reading and processing it. To give you an idea of how these parts are handled, we'll walk you through the basic [A/B testing](https://developer.chrome.com/docs/privacy-sandbox/shared-storage/ab-testing/) example from developer.chrome.com. This example assigns a user to an experiment group, stores the group details in shared storage, and then allows other sites to use that data when choosing a URL to display in a [fenced frame](/en-US/docs/Web/API/Fenced_Frame_API).

Expand All @@ -69,23 +69,23 @@ function getExperimentGroup() {
}

async function injectContent() {
// Assign user to a random group (0 or 1) and store it in Shared Storage
// Assign user to a random group (0 or 1) and store it in shared storage
window.sharedStorage.set("ab-testing-group", getExperimentGroup(), {
ignoreIfPresent: true,
});
}
```

> _Note:_ The `ignoreIfPresent: true` option causes the `set()` function to abort if the shared storage already contains a data item with the specified name.
> _Note:_ The `ignoreIfPresent: true` option causes the `set()` function to abort if the shared storage already contains a data item with the specified key.
### Reading and processing data from shared storage

As mentioned above, to extract useful results from a shared storage worklet you need to use an **output gate**. In this example we'll use the Select URL output gate to read the user's experiment group and then load a URL in a fenced frame based on their group.

To use the output gate, you need to:

- Define an operation in a worklet script to handle choosing the URL, and register it.
- Add the worklet module to your app context.
- Define an operation in a worklet module script to handle choosing the URL, and register it.
- Add the module to your shared storage worklet.
- Choose the URL using the worklet operation and load it in a fenced frame.

Let's look at these one by one.
Expand All @@ -107,7 +107,7 @@ Once the operation is defined, it needs to be registered using {{domxref("Shared
// ab-testing-worklet.js
class SelectURLOperation {
async run(urls, data) {
// Read the user's experiment group from Shared Storage
// Read the user's experiment group from shared storage
const experimentGroup = await this.sharedStorage.get("ab-testing-group");

// Return the corresponding URL (first or second item in the array)
Expand All @@ -122,11 +122,11 @@ Note how the value set in our main app context is retrieved using {{domxref("Wor

#### Add the worklet

To make use of the operation defined in the worklet, it needs to be added to the main app using {{domxref("Worklet.addModule", "window.sharedStorage.worklet.addModule()")}}. This is done in our main app context, before we set the experiment group value, so that it is ready to use when needed:
To make use of the operation defined in the worklet module, it needs to be added to the shared storage worklet using {{domxref("Worklet.addModule", "window.sharedStorage.worklet.addModule()")}}. This is done in our main app context, before we set the experiment group value, so that it is ready to use when needed:

```js
async function injectContent() {
// Register the shared storage worklet
// Add the module to the shared storage worklet
await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");

// Assign user to a random group (0 or 1) and store it in shared storage
Expand Down Expand Up @@ -171,7 +171,7 @@ function getExperimentGroup() {
}

async function injectContent() {
// Register the shared storage worklet
// Add the module to the shared storage worklet
await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");

// Assign user to a random group (0 or 1) and store it in shared storage
Expand Down
67 changes: 67 additions & 0 deletions files/en-us/web/api/sharedstorage/append/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
title: "SharedStorage: append() method"
short-title: append()
slug: Web/API/SharedStorage/append
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SharedStorage.append
---

{{APIRef("Shared Storage API")}}{{SeeCompatTable}}

The **`append()`** method of the
{{domxref("SharedStorage")}} interface appends a string to the value of an existing key/value pair in the current origin's shared storage.

## Syntax

```js-nolint
append(key, value)
```

### Parameters

- `key`
- : A string representing the key of the key/value pair you want to append a string to.
- `value`
- : A string that you want to append to the existing value.

### Return value

A {{jsxref("Promise")}} that fulfills with `undefined`.

### Exceptions

In the case of {{domxref("WindowSharedStorage")}}:

- If the key/value pair doesn't exist in the shared storage, the operation is aborted silently, without rejecting.

In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}}:

- If the key/value pair doesn't exist in the shared storage.
- If the worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}.
- If the appended entry was not successfully stored in the database for some other reason.

In both cases:

- The `Promise` rejects with a {{jsxref("TypeError")}} if `key` and/or `value` exceed the browser-defined maximum length.

## Examples

```js
window.sharedStorage
.append("integer-list", ",9")
.then(console.log("Value appended to integer list"));
```

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- [Shared Storage API](/en-US/docs/Web/API/Shared_storage_API)
53 changes: 53 additions & 0 deletions files/en-us/web/api/sharedstorage/clear/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
title: "SharedStorage: clear() method"
short-title: clear()
slug: Web/API/SharedStorage/clear
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SharedStorage.clear
---

{{APIRef("Shared Storage API")}}{{SeeCompatTable}}

The **`clear()`** method of the
{{domxref("SharedStorage")}} interface clears the current origin's shared storage, removing all data from it.

## Syntax

```js-nolint
clear()
```

### Parameters

None.

### Return value

A {{jsxref("Promise")}} that fulfills with `undefined`.

### Exceptions

In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}}:

- If the worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}.
- If the clearing operation was not successful for some reason.

## Examples

```js
window.sharedStorage.clear().then(console.log("Shared storage cleared"));
```

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- [Shared Storage API](/en-US/docs/Web/API/Shared_storage_API)
64 changes: 64 additions & 0 deletions files/en-us/web/api/sharedstorage/delete/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
title: "SharedStorage: delete() method"
short-title: delete()
slug: Web/API/SharedStorage/delete
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SharedStorage.delete
---

{{APIRef("Shared Storage API")}}{{SeeCompatTable}}

The **`delete()`** method of the
{{domxref("SharedStorage")}} interface deletes an existing key/value pair from the current origin's shared storage.

## Syntax

```js-nolint
delete(key)
```

### Parameters

- `key`
- : A string representing the key of the key/value pair you want to delete.

### Return value

A {{jsxref("Promise")}} that fulfills with `undefined`.

### Exceptions

In the case of {{domxref("WindowSharedStorage")}}:

- If the key/value pair doesn't exist in the shared storage, the operation is aborted silently, without rejecting.

In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}}:

- If the key/value pair doesn't exist in the shared storage, or the delete operation was unsuccessful for some other reason.
- If the worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}.

In both cases:

- The `Promise` rejects with a {{jsxref("TypeError")}} if `key` exceeds the browser-defined maximum length.

## Examples

```js
window.sharedStorage
.delete("ab-testing-group")
.then(console.log("Value deleted"));
```

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- [Shared Storage API](/en-US/docs/Web/API/Shared_storage_API)
51 changes: 51 additions & 0 deletions files/en-us/web/api/sharedstorage/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
title: SharedStorage
slug: Web/API/SharedStorage
page-type: web-api-interface
status:
- experimental
browser-compat: api.SharedStorage
---

{{APIRef("Shared Storage API")}}{{SeeCompatTable}}

The **`SharedStorage`** interface of the {{domxref("Shared Storage API", "Shared Storage API", "", "nocode")}} represents the shared storage for a particular origin, defining methods to write data to the shared storage.

`SharedStorage` is the base class for:

- {{domxref("WindowSharedStorage")}}, accessed via {{domxref("Window.sharedStorage")}}.
- {{domxref("WorkletSharedStorage")}}, accessed via {{domxref("SharedStorageWorkletGlobalScope.sharedStorage")}}.

{{InheritanceDiagram}}

## Instance methods

- {{domxref("SharedStorage.append", "append()")}} {{Experimental_Inline}}
- : Appends a string to the value of an existing key/value pair in the current origin's shared storage.
- {{domxref("SharedStorage.clear", "clear()")}} {{Experimental_Inline}}
- : Clears the current origin's shared storage, removing all data from it.
- {{domxref("SharedStorage.delete", "delete()")}} {{Experimental_Inline}}
- : Deletes an existing key/value pair from the current origin's shared storage.
- {{domxref("SharedStorage.set", "set()")}} {{Experimental_Inline}}
- : Stores new key/value pair in the current origin's shared storage, or updates an existing one.

## Examples

```js
window.sharedStorage
.set("ab-testing-group", "0")
.then(console.log("Value saved to shared storage"));
```

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- {{domxref("WindowSharedStorage")}}
- [Shared Storage API](/en-US/docs/Web/API/Shared_storage_API)
73 changes: 73 additions & 0 deletions files/en-us/web/api/sharedstorage/set/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
title: "SharedStorage: set() method"
short-title: set()
slug: Web/API/SharedStorage/set
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SharedStorage.set
---

{{APIRef("Shared Storage API")}}{{SeeCompatTable}}

The **`set()`** method of the
{{domxref("SharedStorage")}} interface stores new key/value pair in the current origin's shared storage, or updates an existing one.

## Syntax

```js-nolint
set(key, value)
set(key, value, options)
```

### Parameters

- `key`
- : A string representing the key of the key/value pair you want to add or update.
- `value`
- : A string representing the value you want to add or update.
- `options` {{optional_inline}}
- : An options object containing the following properties:
- `ignoreIfPresent`
- : A boolean value that, if set to `true`, will cause the set operation to abort if a key/value pair with the specified `key` already exists. The default value, `false`, will cause the set operation to go ahead and overwrite the previous value, in such cases.

### Return value

A {{jsxref("Promise")}} that fulfills with `undefined`.

### Exceptions

In the case of {{domxref("WindowSharedStorage")}}:

- If the key/value pair doesn't exist in the shared storage, the operation is aborted silently, without rejecting.

In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}}:

- If the worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}.
- If the created/updated entry was not successfully stored in the database for some other reason.

In both cases:

- The `Promise` rejects with a {{jsxref("TypeError")}} if `key` and/or `value` exceed the browser-defined maximum length.

## Examples

```js
window.sharedStorage
.set("ab-testing-group", "0", {
ignoreIfPresent: true,
})
.then(console.log("Set operation completed"));
```

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- [Shared Storage API](/en-US/docs/Web/API/Shared_storage_API)
2 changes: 2 additions & 0 deletions files/en-us/web/api/window/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ Note that properties which are objects (e.g., for overriding the prototype of bu
- : Returns an object reference to the window object itself.
- {{domxref("Window.sessionStorage")}}
- : Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
- {{domxref("Window.sharedStorage")}} {{ReadOnlyInline}}
- : Returns the {{domxref("WindowSharedStorage")}} object for the current origin. This is the main entry point for writing data to shared storage using the [Shared Storage API](/en-US/docs/Web/API/Shared_storage_API).
- {{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
- : Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) speech synthesis functionality.
- {{domxref("Window.statusbar")}} {{ReadOnlyInline}}
Expand Down
Loading

0 comments on commit 7a1984e

Please sign in to comment.