// ab-testing-worklet.js
class SelectURLOperation {
async run(urls, data) {
// Read the user's experiment group from Shared Storage
const experimentGroup = await this.sharedStorage.get("ab-testing-group");
// Return the group number
return experimentGroup;
}
}
// Register the operation
register("ab-testing", SelectURLOperation);SharedStorageSelectURLOperation / notebook
SharedStorageSelectURLOperation
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
// Randomly assigns a user to a group 0 or 1
function getExperimentGroup() {
return Math.round(Math.random());
}
async function injectContent() {
// Register 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
window.sharedStorage.set("ab-testing-group", getExperimentGroup(), {
ignoreIfPresent: true,
});
// Run the URL selection operation
const fencedFrameConfig = await window.sharedStorage.selectURL(
"ab-testing",
[
{ url: `https://your-server.example/content/default-content.html` },
{ url: `https://your-server.example/content/experiment-content-a.html` },
],
{
resolveToConfig: true,
},
);
// Render the chosen URL into a fenced frame
document.getElementById("content-slot").config = fencedFrameConfig;
}
injectContent();