Web SDK
Contentpass library
Contentpass provides website owners with one simple JavaScript client library that acts as the primary interface for all Contentpass-provided functionality.
This functionality currently covers:
- User authentication and authorization
- Rendering of UI widgets
We are very concerned about the loading speed of your website and we do our best to minimize any negative impact on loading speed incurred by our library. We therefore ensure that:
- the initial load is very small
- all components are always loaded async
- all static code is served through a high performance CDN
- assets are aggressively cached wherever possible
Supported URL parameters
For testing your Contentpass integration we provide different query parameters. They can be appended to your page by using the # sign followed by our supported parameters and divided by the & sign known from query parameters, e.g. https://www.example.com/#cpLogging=true. They are creating a local storage entry to save the value and then you can continue testing without the need of appending the query parameters again. If you want to remove the test settings execute another request with empty value, e.g. https://www.example.com/#cpLogging=.
Currently supported query parameters:
- cpLogging (values:
true,falseor empty string to clear)
Initialization
The Contentpass library uses a global cp() command queue to provide all available functionality (very much like the Google Analytics Command Queue that you might be familiar with).
You initialize the Contentpass Command Queue by including the following piece of HTML-code into your website or CMS. This code will asynchronously load the required resources and subsequently initialize the Contentpass Command Queue for the given propertyId that you have received from your Contentpass account representative.
Please be aware that the URL https://static.contentpass.net used in the following snippet is for demonstration purposes only. In this context, you should replace it with the hostname value of the CNAME DNS record created for your property on the publisher dashboard. The format of this hostname should look something like `cp.example.com`.
The propertyId value passed as the second argument to the cp() function in the following snippet is only a placeholder. Please replace it with the property ID value of your property created on the publisher dashboard.
<script>
!function(C,o,n,t,e,P,a,s){C.CPObject=n,C[n]||(C[n]=function(){
for(var i=arguments.length,c=new Array(i),r=0;r<i;r++)c[r]=arguments[r];var f=c[0],u=c[1],l=c[2];if(C[n].q||(C[n].q=[]),
e=Array.prototype.slice.call(arguments,0),!C[n].patched)if("fatal"===f&&u)C[n].le=u,
Array.prototype.forEach.call(C[n].q,(function(e){"error"===e[0]&&"function"==typeof e[1]&&e[1](u)
}));else if("error"===f&&"function"==typeof u)C[n].le&&u(C[n].le);else if("extension"===f&&u)l&&"function"==typeof l.init&&(l.init(),
l.initialized=!0);else if("authenticate"===f&&"function"==typeof u){try{
P=-1===(o.cookie||"").indexOf("_cpauthhint=")&&!(C.localStorage||{})._cpuser&&-1===C.location.href.toLowerCase().indexOf("cpauthenticated")
}catch(e){P=!1}if(P){a={isLoggedIn:function(){return!1},hasValidSubscription:function(){return!1}}
;var p=u,d=!1,h=function(e,i){d||(d=!0,p(e,i))};if(e[1]=h,"function"==typeof o.hasPrivateToken)try{
o.hasPrivateToken(t||"https://my.contentpass.net").then((function(e){e||h(null,a)})).catch((function(){}))
}catch(e){}else h(null,a)}}C[n].q.push(e)});try{
((s=(o.cookie.split("_cpauthhint=")[1]||"").split(";")[0])?Number(s[1]):NaN)>0&&(o.body?o.body.classList.add("cpauthenticated"):o.addEventListener("DOMContentLoaded",(function(){
o.body.classList.add("cpauthenticated")})))}catch(e){}C[n].l=+new Date,C[n].sv=6}(window,document,"cp");
cp('create', 'propertyId');
</script>
<script src="https://static.contentpass.net/now.js" async fetchPriority="high" onerror="cp('fatal', arguments)"></script>
Depending on your use case you can then use all commands that have been activated for your account. You can find a detailed explanation of all available commands and their options below.
For the special case where your website already relies on a global JavaScript variable with the exact name cp this variable can be replaced with > an arbitrary other string during initialization. Afterwards you simply use this name instead of cp to trigger commands.
cp('create', propertyId[, options])
Creates an instance of the Contentpass library.
Currently one instance per browser window is supported.
This command must be called exactly once before any other command is called.
Usage
cp('create', propertyId[, options])
Parameters
| Name | Type | Description | Default | Optional |
|---|---|---|---|---|
| propertyId | string | The property id of your website that you have received from your Contentpass account representative. | ||
| options | object | Optional object containing any of the following optional properties. | Optional | |
| options.baseUrl | string | The Base URL to be used in a first-party implementation. Serves as a shorthand for options.apiUrl, and options.cdnUrl. | undefined | |
| options.apiUrl | string | The URL to be used to connect to our measurement API. This is an advanced feature that should only be used if you provide a proxy endpoint on your domain. | 'https://api.contentpass.net' | |
| options.isSpa | boolean | Define whether your website is a single page application. In this case, automatic page impression counting is disabled and you have to do it manually via the cp('impression') API. | false | |
| options.detectUrl | string | The URL prefix to be used in adblock detection. This is an advanced feature that should only be used when advised by your Contentpass account representative. | ||
| options.cdnUrl | string | The URL prefix to be used to load further assets. This is an advanced feature that should only be used if you host the script yourself. | 'https://static.contentpass.net' | |
| options.setUserContext | function | setUserContext is a function that can be used to provide information about the user to the Contentpass SDK. For example, if you use your own authentication system, the callback passed to this function will allow you to provide the login status and payment status of a user. This way Contentpass can determine if the consent layer should be rendered or not, e.g. it is hidden for a logged-in user with a certain premium subscription. | undefined |
Examples
cp('create', 'b34d7f5a', {
apiUrl: 'https://api.example.com',
cookiePrefix: '_cp',
detectUrl: 'https://my-adserver.example.com/path/to/self/hosted/detection/',
cdnUrl: 'https://static.example.com',
setUserContext: function (cb) {
var ctx = {
// hasAccount: boolean, example based on cookie:
hasAccount: document.cookie.indexOf('myusercookie=') !== -1,
// hasPaidAccess: boolean, example based on cookie:
hasPaidAccess: document.cookie.indexOf('mypremiumcookie=') !== -1,
};
cb(null, ctx);
},
});
Returns
Void
cp('authenticate'[, callback])
Checks the status of the current user with respect to Contentpass.
This operation checks if the user is logged into Contentpass and has valid subscriptions.
Usage
cp('authenticate'[, callback])
Parameters
| Name | Type | Description | Optional |
|---|---|---|---|
| callback | function | An optional callback. | Optional |
Examples
// Check for existing auth cookie/localStorage:
cp('authenticate', function (error, user) {
if (error) {
console.error('Error during user authentication', error);
return;
}
if (user.isLoggedIn() === true) {
console.log('The current visitor is logged in');
}
if (user.hasValidSubscription() === true) {
console.log('User has a valid subscription');
}
});
Returns
Void
cp('render'[, options])
Renders the Contentpass UI widgets into the page.
All configuration for the widgets will be done server-side at Contentpass for your respective propertyId.
Usage
cp('render'[, options])
Parameters
| Name | Type | Description | Optional |
|---|---|---|---|
| options | object | Optional configuration object. The following options are supported: | Optional |
| options.onFullConsent | function | An optional callback to be called whenever all consents have been granted by the user. This is the case when users choose "accept ads" instead of subscribing to Contentpass. You can use this callback to conditionally load your advertising stack in case you do not interact with your CMP directly for that purpose. This callback may be called multiple times per page load, e.g. when the user repeatedly performs opt-out through the CMP, is then again presented with the Contentpass layer, and chooses "accept ads" again. It may also never be called, in particular it will never be called for authenticated Contentpass subscribers (you can also use cp('authenticate') to identify Contentpass subscribers if you need special treatment). |
Examples
// Normal render:
cp('render');
// Perform custom operations once the user has granted all required consents:
cp('render', {
onFullConsent: function () {
console.log('User has given all consents');
},
});
Returns
Void
cp('signup')
Send user to the signup prompt.
Use this function to redirect the user to the signup prompt of the contenpass OpenID Connect authentication flow. For example, when the user clicks on signup button in the cookie banner.
Usage
cp('signup');
Examples
// Send user to signup prompt:
cp('signup');
Returns
Void
cp('login')
Send user to the login prompt.
Use this function to redirect the user to the login prompt of the contenpass OpenID Connect authentication flow. For example, when the user clicks on login link in the cookie banner.
Usage
cp('login');
Examples
// Send user to login prompt:
cp('login');
Returns
Void
cp('logout')
Log out user from current property.
This operation deletes all session information related to the current property. It does not log out of the Contentpass dashboard.
Usage
cp('logout');
Examples
// Logout user from current publisher:
cp('logout');
Returns
Void
cp('impression')
Sends data about a page impression to Contentpass.
This command is used to report a page impression for an authenticated Contentpass user. It can only be used, if you set the option isSpa to true in the call to cp('create'). Otherwise, the command is disabled and nothing is reported.
Usage
cp('impression');
Examples
cp('impression');
Returns
Void
Notes on Availability & Graceful Degradation
While Contentpass offers strong high-availability SLAs, there are several mitigation techniques in place to reduce negative impact on the publisher page in case of an outage on the Contentpass side.
To authenticate users after their first visit to the publisher website, a signed token (JWT) is stored in localstorage and optionally in a cookie (_cpuser). This token is refreshed either when users actively log in or log out, or asynchronously in the background if necessary. The token is set for Contentpass subscribers only.
This means that after the first page impression the authentication logic can run in the client without client-to-server communication.
As a further optimization, when stored as a cookie, this token can also be parsed and verified on the server side allowing the website e.g. to exclude delivery of ad tags for Contentpass subscribers.