The Sesamy browser javascript API
The project handles analytics, authentication and communication with the Seasmy API
The analytics module is used to track events and page views. It is using the GetAnalytics library to send events to the Sesamy interaction endpoint.
The following events are tracked:
- Page views, with events triggered on router updates
- Scroll events, with events triggered on scroll at 25%, 50%, 75%, and 100%
- Active and idle duration
The following methods are available on the sesamy
object:
Certainly! Here’s the list with bullet points sorted alphabetically:
- attributions
- get: get the attributions for a user
- set: set the attributions for a user
- auth
- getUser: fetches the user's profile
- isAuthenticated: checks if the user is authenticated
- loginWithRedirect: redirects the user to the login page
- logout: logs the user out
- setToken: stores a token in session storage
- bills
- get: get a bill by id
- list: lists all the user's bills
- clearCache: clears the cache for the sesamy-js library
- contracts
- cancel: cancel a contract by id
- get: get a contract by id
- list: lists all the user's contracts
- entitlements
- access: fetches the user's access URL for an entitlement
- get: gets a single entitlement by id
- list: lists the user's entitlements
- signedLinks: lists and signedLinks registered in the current session
- fulfillments
- list: list the user's fulfillments for a SKU
- generateLink: creates a link to a Sesamy hosted service such as account, consume, or checkout. If the user is authenticated, the link will be signed so that the user can access the service without logging in again.
- getPaymentIssues: returns a list of failed payments and cards that will expire
- getVersion: returns the version of the sesamy-js library
- init: Initializes the sesamy-js library
- paywalls
- get: get a paywall by id
- product
- autoOnboard: trigger the auto-onboarding process for a product by SKU
- get: get a product by SKU
- profile
- get: fetches the user's profile
- isSpotifyLinked: returns true if the user has linked their Spotify account
- openHostedAccountPage: opens the hosted account page
- unlinkSpotify: unlinks the user's Spotify account
- update: updates the user's profile
- subscriptions (deprecated, use contracts instead)
- list: lists all the user's subscriptions
- tags
- delete: deletes a tag for the user
- get: fetches the user's tags
- set: sets a tag for the user
- tallies
- delete: delete a tally by id
- get: get a tally for a user by id
- list: list all tallies for a user
- push: push an item to a tally
- transactions
- get: get a transaction by id
- list: lists all the user's transactions
- userMetadata
- delete: deletes the user's metadata by id
- get: get the user's metadata by id
- list: list all the user's metadata
- set: sets the user's metadata
The following events are emitted by the sesamy-js library:
-
sesamyJsReady
- Emitted when thesesamy-js
library is ready to be used -
sesamyJsAuthenticated
- Emitted when the user is authenticated -
sesamyJsClearCache
- Emitted when the cache is cleared -
sesamyJsLogout
- Emitted when the user logs out -
sesamyJsPurchase
- Emitted after a purchase is completed and passes an itemSrc property with the source of the purchase
The library can trigger actions based on query parameters. The following query parameters are supported:
-
sesamy-refresh
. If present, the library will clear the cache and emit asesamyJsClearCache
event. -
sesamy-user
. If present, the library will validate that the user is authenticated with the correct email. If not, the user will be logged out and a new login with be initiated. -
sesamy-login
. If present, the library will validate that the user is authenticated. If not, the user will be logged out and a new login with be initiated. -
sesamy-purchase
. Triggers a sesamyJsPurchase event. -
sesamy-token
. If present, the library parse the token and add any content permissions that the token grants.
The library can read the access token from the hash. It is not the preferred way of logging in a user but can be used when redirecting the user across domains where a cookie-based solution is not possible. The hash is not sent to the server so the is no risk of leaking the token. The token hash is passed like this: #access_token=<token>
The script can either be initiated with a JSON object in a script tag or by calling the init method.
The script will look for a script tag with the id sesamy-js
, and if it isn't found it will wait for a call to the init function before initializing. The only required part is the clientId
attribute.
<script type="application/json" id="sesamy-js">
{
"clientId": "demo"
}
</script>
These are the available configuration options, with their default values:
{
clientId: null,
organization: null,
api: {
namespace: 'sesamy',
endpoint: 'https://api2.sesamy.com'
},
analytics: {
enabled: true,
endpoint: 'https://logs.sesamy.com/events'
},
auth: {
clientId: null,
organization: null,
enabled: true,
endpoint: 'https://auth.sesamy.com',
redirectUri: window.location.origin
},
content: {
article: {
article: { selector: 'article' },
image: { selector: 'img', attribute: 'src' },
title: { selector: 'h1', attribute: 'textContent' },
excerpt: { selector: 'p', attribute: 'textContent' },
price: { selector: 'article', attribute: 'data-price' },
currency: { selector: 'article', attribute: 'data-currency' },
url: { selector: 'link', attribute: 'href' },
id: { selector: 'article', attribute: 'data-id' },
pass: { selector: 'article', attribute: 'data-pass' },
}
},
tranforms: {
enabled: false,
rules: []
}
}
Checks if the user is currently authenticated. This function verifies the existence of a valid session by checking both the local storage for an access token and the state of the Auth0 client.
- boolean: Returns
true
if the user is authenticated either via local storage tokens or the Auth0 client; otherwise, it returnsfalse
.
The following example demonstrates how to check if a user is currently authenticated:
import { isAuthenticated } from '@sesamy/sesamy-js';
isAuthenticated()
.then(isAuth => {
if (isAuth) {
console.log('User is authenticated.');
} else {
console.log('User is not authenticated.');
}
})
.catch(error => {
console.error('Error checking authentication status:', error);
});
Initiates a login flow that redirects the user to an Auth0 hosted login page. Once the user authenticates, they will be redirected back to the specified redirect_uri
within your application.
-
options
(optional): An object containing customization options for the login flow.-
appState
: (optional, object) Used to store state before doing the redirect. -
authorizationParams
: (optional, object) Additional parameters to include in the authorization request.-
audience
: (optional, string) The audience to request access to. -
scope
: (optional, string) The scope of the access request. -
login_hint
: (optional, string) A hint to pre-fill the username on the login page. -
organization
: (optional, string) The organization to authenticate with. -
redirect_uri
: (optional, string) The URL to redirect the user to after login.
-
-
This function returns a Promise
that resolves when the redirect is successfully initiated.
The following example demonstrates how to use loginWithRedirect
to initiate a login flow with an email address pre-filled:
import { loginWithRedirect } from '@sesamy/sesamy-js';
// Optionally pass the user's email to pre-fill on the login form
const loginOptions = {
authorizationParams: {
login_hint: 'user@example.com',
},
};
// Redirect the user to the login page
loginWithRedirect(loginOptions);
Terminates the user's session and optionally redirects the user to a specified URL after logout. This function clears any local session tokens and interacts with the Auth0 API to end the session.
-
options
(optional): An object containing customization options for the logout process.-
returnTo
: (optional, string) The URL to redirect users to after logging out. Defaults to the current page URL if not provided.
-
This function does not return a value. It causes a redirect to the specified returnTo
URL or performs a page refresh if no URL is provided.
The following example demonstrates how to log out a user and redirect them to the homepage:
import { logout } from '@sesamy/sesamy-js';
// Specify the URL to redirect to after logout
const logoutOptions = {
returnTo: 'https://www.yourdomain.com',
};
// Redirects the user to the auth server to log out
logout(logoutOptions);
Stores the provided access token in local storage and optionally sets an expiration time for it. Additionally, this function parses the access token to extract user information and triggers an authentication event.
-
accessToken
(string): The access token to store and use for session management. -
expiresIn
(optional, number): The time in seconds from now when the token should expire.
This function does not return a value but triggers an event indicating that a user has been authenticated with the new token.
The following example demonstrates how to store an access token and set an expiration time:
import { setToken } from '@sesamy/sesamy-js';
// Example access token and expiration period
const accessToken = 'your.access.token';
const expiresIn = 3600; // 1 hour in seconds
setToken(accessToken, expiresIn)
.then(() => {
console.log('Token set successfully and user authenticated.');
})
.catch(error => {
console.error('Failed to set token:', error);
});
Fetches a specific entitlement by its ID.
-
entitlementId
(string): The ID of the entitlement to retrieve.
-
Promise<Entitlement | undefined>
: The entitlement object if found, otherwiseundefined
.
// Fetch a specific entitlement by its ID
window.sesamy.entitlements
.get('entitlement-id')
.then(entitlement => {
if (entitlement) {
console.log('Entitlement:', entitlement);
} else {
console.log('Entitlement not found');
}
})
.catch(error => {
console.error('Error fetching entitlement:', error);
});
Fetches the list of entitlements, with optional filters and inclusion of signed links.
-
params
(GetEntitlementsOptions): Optional parameters for fetching entitlements.-
includeSignedLinks
(boolean, optional): Whether to include signed links. Default istrue
. -
waitForEntitlementAfter
(Date, optional): If provided, waits for an entitlement that is available after the given date.
-
-
Promise<Entitlement[]>
: An array of entitlements.
// Fetch all entitlements, including signed links
window.sesamy.entitlements
.list({ includeSignedLinks: true })
.then(entitlements => {
console.log('Entitlements:', entitlements);
})
.catch(error => {
console.error('Error fetching entitlements:', error);
});
Fetches the access details for a specific entitlement by its ID.
-
entitlementId
(string): The ID of the entitlement to access.
-
Promise<Access>
: The access details for the given entitlement.
// Fetch access details for a specific entitlement
window.sesamy.entitlements
.access('entitlement-id')
.then(access => {
console.log('Access details:', access);
})
.catch(error => {
console.error('Error fetching entitlement access:', error);
});
Fetches signed links for the current session's entitlements.
None.
-
SignedLink[]
: An array of signed links for the current entitlements.
// Fetch signed links for the current entitlements
const signedLinks = window.sesamy.entitlements.signedLinks();
console.log('Signed links:', signedLinks);
-
GetEntitlementsOptions: An object containing optional parameters for fetching entitlements.
-
includeSignedLinks
(boolean, optional): Whether to include signed links. Defaults totrue
. -
waitForEntitlementAfter
(Date, optional): A date to filter entitlements that are available after the given date.
-
-
Entitlement: Represents an entitlement object.
-
Access: Represents the access details for an entitlement.
-
SignedLink: Represents a signed link for accessing an entitlement.
Fetches the user's profile information from the Sesamy-hosted service. If the user is authenticated, the profile data will be retrieved.
Promise<Profile | null>
: A promise that resolves to the user's profile information if the user is authenticated, otherwise it resolves to null
.
The following example demonstrates how to fetch the user's profile information:
import { getProfile } from '@sesamy/sesamy-js';
// Fetch the user's profile information
getProfile()
.then(profile => {
if (profile) {
console.log('User profile:', profile);
} else {
console.log('User is not authenticated');
}
})
.catch(error => {
console.error('Error fetching profile:', error);
});
export type Profile = {
userId: string;
firstName?: string;
lastName?: string;
emailVerified: boolean;
email: string;
name?: string;
locale?: string;
picture?: string;
createdAt: string;
updatedAt: string;
mobilePhone?: string;
tags: string[];
user_metadata?: { [id: string]: string | number };
billingAddress?: Address;
deliveryAddress?: Address;
};
export type Address = {
street: string;
co?: string;
city: string;
state: string;
postalCode: string;
country: string;
};
Updates the user's profile information on the Sesamy-hosted service. After updating, the cache is cleared to ensure that the latest profile information is available.
-
profile
(Partial): An object containing the profile fields to be updated. Only the provided fields will be updated.
Promise<boolean>
: A promise that resolves to true
if the profile update is successful, otherwise false
.
The following example demonstrates how to update the user's profile information:
import { updateProfile } from '@sesamy/sesamy-js';
// Define the profile fields to be updated
const updatedProfile = {
firstName: 'John',
lastName: 'Doe',
locale: 'en-US',
mobilePhone: '+1234567890',
};
// Update the user's profile information
updateProfile(updatedProfile)
.then(success => {
if (success) {
console.log('Profile updated successfully');
} else {
console.log('Profile update failed');
}
})
.catch(error => {
console.error('Error updating profile:', error);
});
export type Profile = {
userId: string;
firstName?: string;
lastName?: string;
emailVerified: boolean;
email: string;
name?: string;
locale?: string;
picture?: string;
createdAt: string;
updatedAt: string;
mobilePhone?: string;
tags: string[];
user_metadata?: { [id: string]: string | number };
billingAddress?: Address;
deliveryAddress?: Address;
};
export type Address = {
street: string;
co?: string;
city: string;
state: string;
postalCode: string;
country: string;
};
Generates a link to a Sesamy-hosted service such as account or consume. If the user is authenticated, the link will be signed so that the user can access the service without logging in again.
- params (GenerateAccountLink | GenerateConsumeLink): The parameters for generating the link.
- target (string): The target service, either 'account' or 'consume'.
- sku (string, required for 'consume' target): The SKU of the product to consume.
- episodeId (string, optional for 'consume' target): The ID of the episode to consume.
- shorten (boolean, optional): If true, the link will be shortened.
- ttl (number, optional): The time-to-live for the shortened link in seconds.
- redirectUrl (string, optional): The URL to redirect to after the link is accessed.
- language (string, optional): The language for the link. If not provided the language will be fetched from the HTML element's
lang
attribute.
string: The generated link URL. If shorten is true, the shortened URL is returned.
The following example demonstrates how to generate a link to the Sesamy account page:
import { generateLink } from '@sesamy/sesamy-js';
// Generate a link to the account page
const linkParams = {
target: 'account',
shorten: true,
ttl: 3600, // 1 hour in seconds
redirectUrl: 'https://www.yourdomain.com/account',
};
generateLink(linkParams)
.then(link => {
console.log('Generated link:', link);
})
.catch(error => {
console.error('Error generating link:', error);
});
And here is an example for generating a link to consume a specific product:
import { generateLink } from '@sesamy/sesamy-js';
// Generate a link to consume a product
const linkParams = {
target: 'consume',
sku: 'product-sku',
episodeId: 'episode-id',
shorten: true,
ttl: 3600, // 1 hour in seconds
redirectUrl: 'https://www.yourdomain.com/consume',
};
generateLink(linkParams)
.then(link => {
console.log('Generated link:', link);
})
.catch(error => {
console.error('Error generating link:', error);
});
Creates a checkout session with Sesamy. This function initializes a checkout process by sending the necessary parameters to the Sesamy API.
- params (CreateCheckoutParams): The parameters for creating the checkout session.
- items (Array of objects): An array of items to be included in the checkout.
- sku (string): The SKU of the product to be purchased.
- purchaseOptionsId (string, optional): The ID of the purchase options for the product.
- language (string, optional): The language for the checkout session. If not set, it will be automatically fetched from the HTML element's
lang
attribute. - redirectUrl (string, optional): The URL to redirect to after the checkout process is completed.
- address (Address, optional): The address for the checkout session.
- givenName: (string): The given name.
- familyName: (string): The family name.
- street (string): The street address.
- city (string): The city.
- zip (string): The postal code.
- country (string): The country.
- phoneNumber (string, optional): The phone number.
- email (string, optional): The email address.
- isBusiness (boolean, optional): Indicates if the checkout is for a business.
- paymemtMethodsFilter (Array of objects, optional): The payment methods to be available in the checkout. The payment methods are an object with a provider and a method property, where the method is an optional array.
- items (Array of objects): An array of items to be included in the checkout.
Promise<CheckoutResponse>: A promise that resolves to the response JSON object from the Sesamy API, which contains details about the created checkout session.
- id (string): The unique identifier of the checkout session.
- checkoutUrl (string): The URL for the checkout session.
- status (enum): The status of the checkout session, can be 'PENDING' or 'PAID'.
- createdAt (string): The creation timestamp of the checkout session.
- modifiedAt (string): The last modified timestamp of the checkout session.
- type (enum): The type of checkout session, currently only 'RECURRING' is supported.
- currency (string): The currency used for the checkout session.
- country (string): The country associated with the checkout session.
- redirectUrl (string, optional): The URL to redirect to after the checkout process is completed.
- email (string, optional): The email address for the checkout session.
- language (string): The language used for the checkout session.
- items (Array of objects): The items included in the checkout session.
- sku (string): The SKU of the product.
- purchaseOptionId (string, optional): The ID of the purchase option for the product.
- title (string): The title of the product.
- cover (string): The cover image URL of the product.
- itemsOwned (Array of strings): The SKUs of the items already owned by the user.
- discountCodes (Array of strings): The discount codes applied to the checkout session.
- paymentOptions (Array of objects): The available payment options.
- provider (string): The payment provider.
- methods (Array of strings): The payment methods supported by the provider.
The following example demonstrates how to create a checkout session with Sesamy:
import { createCheckout } from '@sesamy/sesamy-js';
// Create a checkout session with one item
const checkoutParams = {
items: [
{
sku: 'product-sku',
purchaseOptionsId: 'option-id', // optional
},
],
language: 'en', // optional
};
createCheckout(checkoutParams)
.then(response => {
console.log('Checkout session created:', response);
})
.catch(error => {
console.error('Error creating checkout session:', error);
});
In this example, a checkout session is created with a single item specified by its SKU and an optional purchase options ID. The language is set to English ('en'
), but if not provided, it will default to the language specified in the HTML lang
attribute.
- The
language
parameter is optional. If it is not provided, the language will be determined using thegetLanguage
function, which fetches the language from thelang
attribute of the HTML document element. - The
items
array must contain at least one item with a validsku
.
By using the createCheckout
function, you can easily initialize a checkout process and handle the response from the Sesamy API to complete the transaction.
Updates a checkout session with Sesamy.
- params (Partial): The updated parameters for the checkout session.
- items (Array of objects): An array of items to be included in the checkout.
- sku (string): The SKU of the product to be purchased.
- purchaseOptionsId (string, optional): The ID of the purchase options for the product.
- language (string, optional): The language for the checkout session.
- redirectUrl (string, optional): The URL to redirect to after the checkout process is completed.
- email (string, optional): The email address for the checkout session.
- address (Address, optional): The address for the checkout session.
- givenName: (string): The given name.
- familyName: (string): The family name.
- street (string): The street address.
- city (string): The city.
- zip (string): The postal code.
- country (string): The country.
- phoneNumber (string, optional): The phone number.
- email (string, optional): The email address.
- isBusiness (boolean, optional): Indicates if the checkout is for a business.
- items (Array of objects): An array of items to be included in the checkout.
Promise<CheckoutResponse>: A promise that resolves to the response JSON object from the Sesamy API, which contains details about the updated checkout session.
- id (string): The unique identifier of the checkout session.
- checkoutUrl (string): The URL for the checkout session.
- status (enum): The status of the checkout session, can be 'PENDING' or 'PAID'.
- createdAt (string): The creation timestamp of the checkout session.
- modifiedAt (string): The last modified timestamp of the checkout session.
- type (enum): The type of checkout session, currently only 'RECURRING' is supported.
- currency (string): The currency used for the checkout session.
- country (string): The country associated with the checkout session.
- language (string): The language used for the checkout session.
- items (Array of objects): The items included in the checkout session.
- sku (string): The SKU of the product.
- purchaseOptionId (string, optional): The ID of the purchase option for the product.
- title (string): The title of the product.
- cover (string): The cover image URL of the product.
- itemsOwned (Array of strings): The SKUs of the items already owned by the user.
- discountCodes (Array of strings): The discount codes applied to the checkout session.
- paymentOptions (Array of objects): The available payment options.
- provider (string): The payment provider.
- methods (Array of strings): The payment methods supported by the provider.
The following example demonstrates how to create a checkout session with Sesamy:
import { updateCheckout } from '@sesamy/sesamy-js';
// Create a checkout session with one item
const checkoutParams = {
email: 'test@example.com',
};
updateCheckout('checkoutId', checkoutParams)
.then(response => {
console.log('Checkout session updated:', response);
})
.catch(error => {
console.error('Error updating checkout session:', error);
});
In this example, a checkout session is created with a single item specified by its SKU and an optional purchase options ID. The language is set to English ('en'
), but if not provided, it will default to the language specified in the HTML lang
attribute.
- The
language
parameter is optional. If it is not provided, the language will be determined using thegetLanguage
function, which fetches the language from thelang
attribute of the HTML document element. - The
items
array must contain at least one item with a validsku
.
By using the createCheckout
function, you can easily initialize a checkout process and handle the response from the Sesamy API to complete the transaction.
Retrieves the details of a specific checkout session from Sesamy. This function fetches the checkout session information based on the provided checkout session ID.
- id (string): The unique identifier of the checkout session to retrieve.
Promise<CheckoutResponse>: A promise that resolves to the response JSON object from the Sesamy API, which contains details about the requested checkout session.
- id (string): The unique identifier of the checkout session.
- checkoutUrl (string): The URL for the checkout session.
- status (enum): The status of the checkout session, can be 'PENDING' or 'PAID'.
- createdAt (string): The creation timestamp of the checkout session.
- modifiedAt (string): The last modified timestamp of the checkout session.
- type (enum): The type of checkout session, currently only 'RECURRING' is supported.
- currency (string): The currency used for the checkout session.
- country (string): The country associated with the checkout session.
- language (string): The language used for the checkout session.
- items (Array of objects): The items included in the checkout session.
- sku (string): The SKU of the product.
- purchaseOptionId (string, optional): The ID of the purchase option for the product.
- title (string): The title of the product.
- cover (string): The cover image URL of the product.
- itemsOwned (Array of strings): The SKUs of the items already owned by the user.
- discountCodes (Array of strings): The discount codes applied to the checkout session.
- paymentOptions (Array of objects): The available payment options.
- provider (string): The payment provider.
- methods (Array of strings): The payment methods supported by the provider.
The following example demonstrates how to retrieve the details of a specific checkout session with Sesamy:
import { getCheckout } from '@sesamy/sesamy-js';
// Retrieve the details of a checkout session by ID
const checkoutId = 'checkout-session-id';
getCheckout(checkoutId)
.then(response => {
console.log('Checkout session details:', response);
})
.catch(error => {
console.error('Error retrieving checkout session:', error);
});
In this example, the details of a specific checkout session are retrieved using its unique ID. The function returns a promise that resolves to the details of the checkout session.
- The
id
parameter is required and must be a valid checkout session identifier.
By using the getCheckout
function, you can easily fetch the details of a specific checkout session from the Sesamy API to view or process the transaction information.
Detects the presence of an ad blocker in the browser by dynamically creating and checking the visibility of several ad-related HTML elements.
None
Promise: A promise that resolves to a boolean value indicating whether an ad blocker is enabled (true
) or not (false
).
The following example demonstrates how to use the detectAdblock
function to detect if an ad blocker is enabled:
import { detectAdblock } from '@sesamy/sesamy-js';
// Detect if an ad blocker is enabled
detectAdblock()
.then(isAdblockEnabled => {
if (isAdblockEnabled) {
console.log('Adblocker is enabled');
} else {
console.log('Adblocker is not enabled');
}
})
.catch(error => {
console.error('Error detecting adblock:', error);
});
- The function creates a set of HTML
<div>
elements with IDs typically used by ad containers (e.g., 'AdHeader', 'AdContainer', etc.). - These elements are appended to the body of the document and their visibility is checked after a short delay (100 milliseconds).
Detects if the browser is running in incognito mode.
None
Promise: A promise that resolves to a boolean value indicating whether the browser is running in incognito mode (true
) or not (false
).
The following example demonstrates how to use the isIncognito
function:
import { isIncognito } from '@sesamy/sesamy-js';
// Detect if browser is running in incognito mode
isIncognito().then(isIncognitoEnabled => {
if (isIncognitoEnabled) {
console.log('Incognito mode is enabled');
} else {
console.log('Incognito mode is not enabled');
}
});
Detects if the current browsing context is an in-app browser and identifies the browser name if applicable.
None
Object: An object containing two properties:
-
isInAppBrowser
(boolean): Indicates whether the current browsing context is an in-app browser (true
) or not (false
). -
browserName
(string | null): The name of the in-app browser if detected, ornull
if not detected.
The following example demonstrates how to use the isInAppBrowser
function to check if the current context is an in-app browser and log the browser name if applicable:
import { isInAppBrowser } from '@sesamy/sesamy-js';
// Detect if the current context is an in-app browser
const result = isInAppBrowser();
if (result.isInAppBrowser) {
console.log(`Running inside an in-app browser: ${result.browserName}`);
} else {
console.log('Not running inside an in-app browser');
}
- A predefined list of common in-app browsers (e.g., Facebook, Instagram, LinkedIn, etc.) is checked against the user agent.
- If a match is found, the function returns
isInAppBrowser: true
and the correspondingbrowserName
. - If no known in-app browser signatures are detected, the function returns
isInAppBrowser: false
andbrowserName: null
.
The transform module allows for dynamic content manipulation based on specified rules. This can include inserting, replacing, or removing elements on a webpage.
The transform configuration is defined within the Config
interface. The following properties are available:
-
enabled
(boolean, optional): Enables or disables the transform module. -
rules
(array): An array of rule objects that define the transformations to apply.
Each rule object contains the following properties:
-
selector
(string): A CSS selector to target elements on the page. -
transform
(string): The type of transformation to apply. Valid values are 'insert', 'replace', 'remove' and 'gradient'. -
content
(string, optional): The content to insert or replace. Required for 'insert' and 'replace' transforms. - 'insertPosition' (string, optional): The position to insert the content. Valid values are 'before', 'after' and 'insider'.
-
contentType
(string, optional): Specifies the type of content. Valid values are 'html', 'selector', and 'url'. -
path
(string, optional): A regular expression to match the URL path. If provided, the rule will only apply when the path matches the current URL. -
entitlement
(string, optional): Specifies an entitlement required for the rule to apply. -
authenticated
(boolean, optional): Specifies if the rule should only apply to authenticated users.
Below is an example configuration for the transform module:
{
"transform": {
"enabled": true,
"rules": [
{
"selector": "#example",
"transform": "replace",
"content": "<p>New content</p>",
"contentType": "html"
},
{
"selector": ".ad-banner",
"transform": "remove"
},
{
"selector": ".insert-content",
"transform": "insert",
"content": "#source-element",
"contentType": "selector"
},
{
"selector": ".load-from-url",
"transform": "insert",
"content": "https://example.com/content",
"contentType": "url"
}
]
}
}
To use the transform module, include the configuration in your initialization script:
<script type="application/json" id="sesamy-js">
{
"clientId": "demo",
"transform": {
"enabled": true,
"rules": [
{
"selector": "#example",
"transform": "replace",
"content": "<p>New content</p>",
"contentType": "html"
},
{
"selector": ".ad-banner",
"transform": "remove"
},
{
"selector": ".insert-content",
"transform": "insert",
"content": "#source-element",
"contentType": "selector"
},
{
"selector": ".load-from-url",
"transform": "insert",
"content": "https://example.com/content",
"contentType": "url"
}
]
}
}
</script>
This configuration will replace the content of the element with the ID example
, remove elements with the class ad-banner
, insert the content of the element with the ID source-element
into elements with the class insert-content
, and load content from a URL into elements with the class load-from-url
.
The content module allows you to extract dynamic article data from a webpage based on specific selectors. This can include elements like the title, image, excerpt, price, and more.
The content configuration is defined within the Config
json. The following properties are available:
-
article
(object): Defines the selector for the article element itself. -
image
(object): Specifies the selector and attribute for extracting article images. -
title
(object): Specifies the selector and attribute for extracting the article title. -
excerpt
(object): Specifies the selector and attribute for extracting the article excerpt. -
price
(object): Specifies the selector and attribute for extracting the article price. -
currency
(object): Specifies the selector and attribute for extracting the article currency. -
url
(object): Specifies the selector and attribute for extracting the article URL. -
id
(object): Specifies the selector and attribute for extracting the article ID.
Each field object contains the following properties:
-
selector
(string): A CSS selector to target elements on the page. -
attribute
(string, optional): The attribute to retrieve from the selected element. If not specified, the text content of the element is used.
Below is an example configuration for the content module:
{
"content": {
"article": {
"selector": "article"
},
"image": {
"selector": "img",
"attribute": "src"
},
"title": {
"selector": "h1",
"attribute": "textContent"
},
"excerpt": {
"selector": "p",
"attribute": "textContent"
},
"price": {
"selector": "article",
"attribute": "data-price"
},
"currency": {
"selector": "article",
"attribute": "data-currency"
},
"url": {
"selector": "link",
"attribute": "href"
},
"id": {
"selector": "article",
"attribute": "data-id"
}
}
}
To use the content module, initialize it with the appropriate configuration:
import { init } from '@sesamy/sesamy-js';
init({
content: {
article: { selector: 'article' },
image: { selector: 'img', attribute: 'src' },
title: { selector: 'h1', attribute: 'textContent' },
excerpt: { selector: 'p', attribute: 'textContent' },
price: { selector: 'article', attribute: 'data-price' },
currency: { selector: 'article', attribute: 'data-currency' },
url: { selector: 'link', attribute: 'href' },
id: { selector: 'article', attribute: 'data-id' },
},
});
Returns an array of article objects containing the extracted data for each article on the page.
Each article object contains the following properties:
-
title
(string, optional): The title of the article. -
excerpt
(string, optional): The article's excerpt. -
image
(string, optional): The source URL of the article's image. -
price
(number, optional): The price of the article. -
currency
(string, optional): The currency of the article price. -
url
(string, optional): The URL of the article. -
id
(string, optional): The article's unique ID. -
element
(Element): The original DOM element for the article.
import { init } from '@sesamy/sesamy-js';
const sesamyjs = await init({ ...config });
// Extract and log all content
const articles = sesamy.content.list();
console.log(articles);
In this example, content.list()
will return an array of articles extracted from the page based on the configured selectors. Each article object contains fields such as title, excerpt, image, price, currency, URL, and ID.
The library polyfills the following methods for compatibility with older browsers:
- URL
- URLSearchParams
- fetch
- The
content
property is required for 'insert' and 'replace' transforms. - The
contentType
property specifies how to interpret thecontent
property: as raw HTML, a CSS selector, or a URL to fetch content from. - The
path
property can be used to apply rules conditionally based on the current URL. - The
authenticated
property ensures that rules only apply to authenticated users if set to true.
The library tracks the following data for attribution purposes and pass it on to the checkout when initiating a purchase:
-
utm_source
: The source of the traffic. -
utm_medium
: The medium of the traffic. -
utm_campaign
: The campaign associated with the traffic. -
utm_term
: The term associated with the traffic. -
utm_content
: The content associated with the traffic. -
ref
: The referrer passed in the querystring. -
referrer
: The referrer URL of the initial page load. -
item-src
: The url of the last locked article viewed.