Javascript SDK
This documentation covers all the features provided in the Javascript SDK: the 'consent.js' file. If you want to learn more about our Right Consents solution, please refer to the appropriate documentation.
This documentation references most classes and methods available within the consent.js typescript library.
Prerequisites
We are assuming here that you have sufficient knowledge of the javascript environment and web development. We are also assuming you are familiar with the terminology of the FairAndSmart Right Consents solution, as well as the tools provided. If this is not the case, please refer to our documentation before continuing.
Import Consent.js
Import the consent.js file on all webpages where you are using Right Consents features.
The file must always be imported from the official FairAndSmart asset server or with npm.
NPM module (recommended)
We also provide the @fairandsmart/consent-manager module in the public npm directory. You can install it in your project with the following command:
$ npm i @fairandsmart/consent-manager
You can then import any component of the SDK with the import
keyword.
Example:
import { ConsentCollector } from '@fairandsmart/consent-manager';
const collector = new ConsentCollector();
The NPM module provides typings compatible with Typescript. This version allows an optimal and simpler development environment than the Javascript version imported below with the script tag.
Script tag
We provide the Consent.js file through our official asset server.
<script src="https://assets.fairandsmart.tech/consent.js"></script>
When the consent.js file is imported via a script tag, the SDK features are available in the window.FairAndSmart
global variable of your web page.
Example:
const collector = new FairAndSmart.ConsentCollector();
The version of Consent.js imported from our asset server contains only the native javascript sources, without typings. If you prefer to develop more complex solutions, please use the npm module.
Initialize Consent.js
The SDK needs to be initialized before being used. Depending on your offers configuration and on what you wish to achieve with Consent.js, you will need to specify the various access points to FairAndSmart services.
If you only wish to use Consent.js for its included types, interfaces and enumerations, you can skip this step.
Before using the collection functionalities of the SDK, you must call the RightConsents.init
method:
import { RightConsents } from '@fairandsmart/consent-manager';
import { defaultHttpClient } from '@fairandsmart/consent-manager/http';
RightConsents.init({
apiRoot: 'https://consent-manager.fairandsmart.com',
catalogRoot: 'https://catalog.fairandsmart.com',
httpClient: defaultHttpClient,
});
This method takes as parameter a configuration object with the following fields:
Field | Description | Default value |
---|---|---|
apiRoot | The access point to your FairAndSmart Consent Manager. The SDK will use this URI to interrogate your user consent database. | ‘no_endpoint’ |
catalogRoot | The access point to your FairAndSmart data catalog. This option needs to be specified only if you subscribed to the Right Data offer - allowing you to collect user data. | ‘no_endpoint’ |
httpClient | The HTTP client through which all the SDK calls will transit. The function must be of type RcHttpClient. You may choose to use the HTTP client of the SDK (defaultHttpClient) or implement yours. | defaultHttpClient |
This call is synchronous and initializes the Javascript library in its entirety. Be careful to execute this action before anything else.
Types and interfaces
The @fairandsmart/consent-manager
module contains types and interface definitions in Typescript, as well as helpers to quickly use the Right Consents API with full compatibility.
Usage
All the components of the library are accessible by importing them from their respective endpoints. The library is organized according to the Right Consents API resources.
You can directly import an element from the sub-resource in the import path (recommended).
import { ConsentContext } from '@fairandsmart/consent-manager/consents';
const context: ConsentContext = { ... };
You can also import each resource into a wrapper containing all its components like this: (not recommended - not very readable)
import { ConsentsResource } from '@fairandsmart/consent-manager';
const context: ConsentsResource.ConsentContext = { ... };
Interfaces
In TypeScript, an interface is a construct that determines the signature of an object. Unlike classes, they do not need to be instantiated with the new keyword and can be assigned to javascript objects at any time. They allow a better readability of the code and ensure its compatibility.
Many interfaces are available in @fairandsmart/consent-manager
and if you use TypeScript, when you use a method of the library, you will have access to the variety of definitions available to you.
Helpers
Helpers are static classes that allow us to manipulate our objects and data in different ways.
ModelEntryHelper
getActiveVersionIdentifier
This method takes as parameter a template (of consent, preference, email...) and returns the unique identifier of the version with the ACTIVE
status.
import { ModelEntryHelper } from '@fairandsmart/consent-manager/models';
const model: Processing = getProcessingModel(); // Model recuperation (example)
const activeVersionId: string = ModelEntryHelper.getActiveVersionIdentifier(model);
console.log(activeVersionId);
// => "processing/processing.001/s3riAl"
getActiveVersion
This method retrieves the version of the model passed in the parameter with the ACTIVE
status.
Only one version can have this status at a time per model.
import { ModelEntryHelper } from '@fairandsmart/consent-manager/models';
const model: Processing = getActiveProcessingModel(); // Model recuperation (example)
const activeVersion: ModelVersionDtoLight<Processing> = ModelEntryHelper.getActiveVersion(model);
hasActiveVersion
This method returns true
if there is a version with the status ACTIVE
for the model passed in parameter.
import { ModelEntryHelper } from '@fairandsmart/consent-manager/models';
const model: Processing = getProcessingModel(); // Model recuperation (example)
ModelEntryHelper.hasActiveVersion(model);
// => true
ConsentHelper
generateContextFromRecord This method takes as parameters a model, a record and a language. It then returns a new context that is valid and compatible with the record passed as parameter. This allows to quickly regenerate a new collection context for a user who has already given a consent in the past.
import { ConsentHelper} from '@fairandsmart/consent-manager/consents';
const model: Processing = getProcessingModel(); // Model recuperation (example)
const record: RecordDto = getRecordForModel(model); // Model's record recuperation
const newContext: ConsentContext = ConsentHelper.generateContextFromRecord(model, record, 'fr');
API Calls
Consent.js implements a library of methods to interface with the Right Consents API.
These methods define parameters in input and output of each endpoint, and use an HTTP request function.
HTTP Client
In order for the API call methods to work properly, an HTTP Client must be provided to the library. There is one by default, but it may not meet all your needs.
The HTTP client must correspond to an object of type RcHttpClient, available from @fairandsmart/consent-manager/http
Here is an example of creating a compatible HTTP client, followed by the use of an API call method.
import { RightConsents, RcHttpClientConfig } from '@fairandsmart/consent-manager';
// HTTP client creation
function myCustomHttpClient(config: RcHttpClientConfig): Observable<ModelEntryDto> {
// Add an API key, an oAuth workflow, etc - then make the HTTP call.
return fromFetch(config.url, ...);
}
// RightConsents library initialization
RightConsents.init({
apiRoot: 'https://consent-manager.fairandsmart.com',
catalogRoot: 'https://catalog.fairandsmart.com',
httpClient: myCustomHttpClient,
});
// API call with an observable...
ModelsResource.getEntry(entryId).subscribe((modelEntry: ModelEntryDto) => {
...
});
// ... or with a promise, using .toPromise()
const modelEntry: ModelEntryDto = await ModelsResource.getEntry(entryId).toPromise();
For more details on the available methods, please see the list here.
Forms
Consent.js provides complete data consent collection scenario integrations in Javascript, compatible with any web or mobile browser.
ConsentCollector
This scenario allows the collection of a set of processing and preferences in an existing workflow.
With Consent.js
<html>
<head>
<script src="https://assets.fairandsmart.tech/consent.js"></script>
</head>
<body>
<button onclick="collect()">Collect consent</button>
<script>
function collect() {
const consentCollector = new FairAndSmart.ConsentCollector({
tokenBrokerEndpoint: 'https://proxy-consent.yourdomain.com/profile/form', // This is the URL from which you will generate a consent transaction token.
consentContext: {
subject: 'YOUR USER ID', // The unique user identifier. Implementing an authenticated solution is up to you, if necessary.
author: 'YOUR USER ID', // In this case, the unique user identifier.
origin: "WEBFORM", // WEBFORM means that the user is directly interacting with an online form to submit their consent.
confirmation: "NONE", // The confirmation method (none, email, sms...) to use to validate the consent submission.
language: "en", // The collection language.
userinfos: {}, // Additional user information that you wish to share.
validity: "P6M", // Validity period (in the DateInterval format).
layout: "layout.001" // The identifying key of the Layout model that you designed in the backoffice.
},
mode: 'window' // The consent window display mode ('window' or 'iframe').
});
consentCollector.collect() // Starts the consent collection process (asynchronous).
.then(() => {
// The process worked fine and is finished.
})
.catch((err) => {
// Handle any error.
});
}
</script>
</body>
</html>
With @fairandsmart/consent-manager
import { ConsentCollector } from '@fairandsmart/consent-manager';
function collect() {
const consentCollector = new ConsentCollector({
tokenBrokerEndpoint: 'https://proxy-consent.yourdomain.com/profile/form', // This is the URL from which you will generate a consent transaction token.
consentContext: {
subject: 'YOUR USER ID', // The unique user identifier. Implementing an authenticated solution is up to you, if necessary.
author: 'YOUR USER ID', // In this case, the unique user identifier.
origin: "WEBFORM", // WEBFORM means that the user is directly interacting with an online form to submit their consent.
confirmation: "NONE", // The confirmation method (none, email, sms...) to use to validate the consent submission.
language: "en", // The collection language.
userinfos: {}, // Additional user information that you wish to share.
validity: "P6M", // Validity period (in the DateInterval format).
layout: "layout.001" // The identifying key of the Layout model that you designed in the backoffice.
},
mode: 'window' // The consent window display mode ('window' or 'iframe').
});
consentCollector.collect() // Starts the consent collection process (asynchronous).
.then(() => {
// The process worked fine and is finished.
})
.catch((err) => {
// Handle any error.
});
}
DataCollector
This scenario allows the collection of encrypted data from the user. From a schema configuration (defined in our backoffice in Right Data > Schemas), a data form will be generated and replace a tag in your HTML page.
Once the user has filled in the data, and you have performed the required processing, the data will be encrypted and sent to our secure servers. You will be able to consult them from our backoffice and perform additional operations according to your offers.
With Consent.js
<html>
<head>
<script src="https://assets.fairandsmart.tech/consent.js"></script>
</head>
<body>
<form id="myform"></form>
<script>
const dataCollector = new FairAndSmart.DataCollector({
dataCreationEndpoint: 'http://proxy-fs.domain.com/data/form', // The URL to which the data will be sent (see the "proxy" section for more information)
elementId: 'my-form', // The identifier of the HTML tag to replace
schemaName: 'Contact', // The name of the schema to use (see backoffice)
schemaPrefix: 'mycompany', // The schema prefix (see backoffice)
userFieldId: 'e58d6366-4608-4d87-a1f5-da0826e13158', // The identifier (from the schema) of the field to use as identifier for the user
dataSentTemplate: `<strong>Vos informations ont bien été envoyée avec votre consentement !</strong>` // The HTML template which will replace the form once it has been submitted
});
dataCollector.render(); // Replace the <form> tag with the generated form.
/** Use the power of rxjs to follow the progression of the data collection. */
dataCollector.onSend().pipe(
mergeMap((dataStore) => {
/** If this code is executed, it means that the user clicked on "Send" and that a DataStore has been created.
* Do all the actions that you want here, before sending the data to our servers.
*/
return dataCollector.pushData();
})
).subscribe({
next: () => { /** Success callback (the data have been sent) */ },
error: (err) => { /** Error callback */ },
});
</script>
</body>
</html>
With @fairandsmart/consent-manager
import { DataCollector} from '@fairandsmart/consent-manager';
const dataCollector = new DataCollector({
dataCreationEndpoint: 'http://proxy-fs.domain.com/data/form', // The URL to which the data will be sent (see the "proxy" section for more information)
elementId: 'my-form', // L'id de la balise HTML à remplacer
schemaName: 'Contact', // The name of the schema to use (see backoffice)
schemaPrefix: 'mycompany', // The schema prefix (see backoffice)
userFieldId: 'e58d6366-4608-4d87-a1f5-da0826e13158', // The identifier (from the schema) of the field to use as identifier for the user
dataSentTemplate: `<strong>Vos informations ont bien été envoyée avec votre consentement !</strong>` // The HTML template which will replace the form once it has been submitted
});
dataCollector.render(); // Replace the <form> tag with the generated form.
/** Use the power of rxjs to follow the progression of the data collection. */
dataCollector.onSend().pipe(
mergeMap((dataStore) => {
/** If this code is executed, it means that the user clicked on "Send" and that a DataStore has been created.
* Do all the actions that you want here, before sending the data to our servers.
*/
return dataCollector.pushData();
})
).subscribe({
next: () => { /** Success callback (the data have been sent) */ },
error: (err) => { /** Error callback */ },
});