### Block Inline Script Resources with Didomi
Source: https://docs.contentpass.net/docs/onboarding/cmp/didomi
This example shows how to wrap inline scripts with a Didomi-specific script tag to control their execution based on user consent. It requires adding data-vendor and data-purposes attributes to the wrapper.
```html
```
--------------------------------
### Contentpass Token Payload Examples
Source: https://docs.contentpass.net/docs/token
Illustrates the JSON structure of the Contentpass token payload for both users who are not signed in and users who have a valid subscription.
```json
{
"auth": false,
"plans": [],
"aud": "fade8c10",
"iat": 1636040380,
"exp": 1636216780
}
```
```json
{
"auth": true,
"plans": ["ca492af7-320c-42c9-9ba0-b2a33cfca307"],
"aud": "fade8c10",
"iat": 1636039699,
"exp": 1636216099
}
```
--------------------------------
### Open CMP Settings Layer with __cmp('showScreenAdvanced')
Source: https://docs.contentpass.net/docs/onboarding/cmp/consentmanager
Allow users to open the CMP settings layer by calling the `__cmp('showScreenAdvanced')` SDK function. This can be easily implemented by adding a link with an `onclick` handler in your footer.
```html
Open Consent Settings
```
--------------------------------
### Advanced CSS for Authenticated Users (HTML/CSS)
Source: https://docs.contentpass.net/docs/onboarding/cmp
Demonstrates advanced CSS usage with the 'cpauthenticated' class to selectively hide elements. This example hides containers with the class 'ads' that contain links to external domains, excluding your own. It requires a modern browser supporting :has() pseudo-class.
```html
adserver.com
example.com
```
--------------------------------
### Create Contentpass Instance
Source: https://docs.contentpass.net/docs/web-sdk
This command initializes a single instance of the contentpass library for the current browser window. It must be called exactly once before any other contentpass commands are executed. The 'propertyId' is a required argument, and optional parameters can also be provided.
```javascript
cp('create', propertyId[, options])
```
--------------------------------
### Block Scripts Specifically for Contentpass Users
Source: https://docs.contentpass.net/docs/onboarding/cmp/consentmanager
Provides an example of how to add a custom attribute to inline scripts to block them specifically for contentpass users. This is an additional feature to the manual blocking method and helps avoid loading resources regardless of consent state.
```html
```
--------------------------------
### Initialize Contentpass Library
Source: https://docs.contentpass.net/docs/web-sdk
This snippet initializes the contentpass Command Queue by including a script in your website's HTML. It asynchronously loads necessary resources and sets up the command queue for a given property ID. Ensure you replace placeholder URLs and IDs with your actual values. The script also handles authentication state by adding a class to the body.
```html
```
--------------------------------
### Hide Ads with Specific Hrefs using CSS
Source: https://docs.contentpass.net/docs/onboarding/cmp/usercentrics
This CSS example demonstrates how to hide elements with the class 'ads' that contain anchor tags with an href starting with 'http' but not containing 'example.com/'. It's useful for filtering external ads. Requires a CSS-enabled environment.
```css
body.cpauthenticated
.ads:has(a[href^="http"]:not([href*="example.com/"])) {
display: none;
}
```
--------------------------------
### Initialize ContentPass SDK
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
Initializes the ContentPass SDK with a given property ID and base URL. This is a fundamental step before using other ContentPass functionalities. It ensures the SDK is ready to communicate with the ContentPass service.
```javascript
cp('create', cpPropertyId, {
baseUrl: cpBaseUrl
});
```
--------------------------------
### Server-side Token Validation
Source: https://docs.contentpass.net/docs/token
Provides a guide on how to validate the Contentpass JWT token on your backend to verify user authentication and subscription status.
```APIDOC
## Server-side Token Validation
### Description
To ensure the integrity and validity of the Contentpass token on your server, you must perform several checks on the received JWT. This process allows you to confidently determine user authentication and subscription details.
### Validation Steps
1. **JWT Format Verification**: Ensure the token adheres to the JWT structure (three base64-encoded parts separated by dots).
2. **Signature Verification**: Verify the token's signature using the public RSA keys.
* **OIDC Configuration**: Obtain the OIDC configuration endpoint from `https://my.contentpass.net/.well-known/openid-configuration`. This will provide the `jwks_uri` (e.g., `https://my.contentpass.net/auth/oidc/jwks`).
* **Key Retrieval**: Use the key ID (`kid`) from the token header to select the appropriate public key from the JWKS endpoint. If no `kid` is present, try all provided keys.
* **Library Usage**: Utilize recommended JWT libraries (e.g., from [jwt.io](https://jwt.io/libraries)) for signature validation.
* **Key Caching**: Cache the JWKS endpoint results for no longer than 1 hour. Be prepared for potential key rotations.
3. **Payload Claims Verification**: Check the following claims within the token's payload:
* `"auth"`: Must be set to `true`.
* `"plans"`: Must contain at least one plan identifier.
* `"aud"` (Audience): Must match your specific property ID. Note that mobile apps may have different property IDs than websites.
* `"iat"` (Issued At): Must be a timestamp from the past, allowing for a small buffer (e.g., a few minutes) to account for clock drift.
* `"exp"` (Expiration): While the token has an expiration time, the documentation advises *not* to check if it lies in the future, implying that the signature and other claims are the primary validation points for ongoing use, with the SDK handling refreshes.
```
--------------------------------
### ContentPass Initialization and Rendering
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
Initializes the ContentPass JavaScript library and triggers the rendering of the consent layer. It handles user authentication status to conditionally display the consent layer.
```javascript
(function() {
var cpBaseUrl = 'https://cp.example.com';
var cpController = cpBaseUrl + '/now.js';
var cpPropertyId = '1234abcd';
!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;r0&&(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', cpPropertyId, {
baseUrl: cpBaseUrl
});
cp('render', {
onFullConsent: function() {
console.log('[CP] onFullConsent');
}
})
})()
```
--------------------------------
### Didomi SDK Initialization (JavaScript)
Source: https://docs.contentpass.net/docs/onboarding/cmp/didomi
This code snippet demonstrates the initialization of the Didomi SDK, which is responsible for managing user consent. It includes functions to handle iframe creation and event listeners for SDK readiness.
```javascript
```
--------------------------------
### Block Inline Script Resources with Consentmanager
Source: https://docs.contentpass.net/docs/onboarding/cmp/consentmanager
Modifies inline script tags to block their execution until user consent is obtained. This is achieved by changing the script type and adding specific data attributes, ensuring compliance with consent requirements.
```html
```
--------------------------------
### Initialize ContentPass SDK
Source: https://docs.contentpass.net/docs/web-sdk
Initializes the ContentPass SDK with a property ID and optional configuration. This function sets up the SDK for use on your website. It accepts a property ID and an options object for advanced configurations like custom API URLs, CDN URLs, and user context functions.
```javascript
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);
},
});
```
--------------------------------
### Load Didomi SDK
Source: https://docs.contentpass.net/docs/onboarding/cmp/didomi
This JavaScript snippet dynamically loads the Didomi SDK, configuring it with the provided API key and user location data. It sets up preconnect and dns-prefetch links for the SDK domain and asynchronously loads the loader script.
```javascript
(function(){(function(e){var r=document.createElement('link');r.rel='preconnect';r.as='script';
var t=document.createElement('link');t.rel='dns-prefetch';t.as='script';var n=document.createElement('script');
n.id='spcloader';n.type='text/javascript';n['async']=true;n.charset='utf-8';
var o='https://sdk.privacy-center.org/'+e+'/loader.js?target='+document.location.hostname;
if(window.didomiConfig&&window.didomiConfig.user){var i=window.didomiConfig.user;var a=i.country;var c=i.region;
if(a){o=o+'&country='+a;if(c){o=o+'®ion='+c;}}}r.href='https://sdk.privacy-center.org/';t.href='https://sdk.privacy-center.org/';
n.src=o;var d=document.getElementsByTagName('script')[0];d.parentNode.insertBefore(r,d);d.parentNode.insertBefore(t,d);
d.parentNode.insertBefore(n,d);})("{{YOUR_API_KEY}}")})();
```
--------------------------------
### Block Iframe/Embed Resources with Consentmanager
Source: https://docs.contentpass.net/docs/onboarding/cmp/consentmanager
Demonstrates how to modify iframe tags to block embedded resources until consent is granted. This involves changing the src attribute, adding a new src, and including specific classes and data attributes for consent management.
```html
```
--------------------------------
### Block External Script Resources with Consentmanager
Source: https://docs.contentpass.net/docs/onboarding/cmp/consentmanager
Modifies script tags to block external resources until consent is given. It involves changing the script type and adding data attributes. This method ensures contentpass functions correctly by deferring resource loading.
```html
```
--------------------------------
### Sourcepoint Configuration Object
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
Defines the configuration object for Sourcepoint, typically assigned to `window._sp_`. This object is crucial for initializing and customizing Sourcepoint's behavior, including settings related to privacy, consent, and messaging.
```javascript
window._sp_ = {
config: {
```
--------------------------------
### Preconnect to ContentPass Servers
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
This HTML snippet adds a preconnect link element to the head of a website. It instructs the browser to initiate an early connection to the specified server (using a CNAME for your property), which helps improve the initial loading time of the SDK.
```html
```
--------------------------------
### Server-Side Cookie Authentication Check (Node.js)
Source: https://docs.contentpass.net/docs/onboarding/cmp/usercentrics
This Node.js example shows how to implement middleware to check the '_cpauthhint' cookie for ContentPass user authentication. It sets a request property 'isLoggedInCpUser' to determine user type for rendering different views. Requires Node.js environment with cookie-parsing middleware.
```javascript
// Middleware to check the "_cpauthhint" cookie
function checkUserType(req, res, next) {
const cpAuthHintCookie = req.cookies._cpauthhint;
// Check if the cookie exists and has the value for a logged in CP user
req.isLoggedInCpUser = cpAuthHintCookie === '1';
next();
}
// Route that uses the authentication middleware
app.get('/dashboard', checkUserType, function (req, res) {
// Render different views for ContentPass users and regular users
if (req.isCpUser) {
res.render('dashboard', { user: 'ContentPassUser', showAdblockCommunication: false });
} else {
res.render('dashboard', { user: 'RegularUser', showAdblockCommunication: true });
}
});
```
--------------------------------
### Load Third-Parties for Non-Contentpass Users (JavaScript)
Source: https://docs.contentpass.net/docs/3rdparty
This JavaScript snippet demonstrates how to use the `cp('authenticate')` function to check a user's Contentpass login and subscription status. If the user is neither logged in nor has a valid subscription, it provides a callback function where you can implement logic to load third-party resources. It includes placeholder variables for `cpBaseUrl` and `cpPropertyId` that need to be replaced with actual values. Note that this check is independent of TCF consent, and additional measures might be needed for full GDPR compliance.
```javascript
// CP parameters
var cpBaseUrl = 'https://cp.example.com';
var cpPropertyId = '1234abcd';
// Regular stub
// prettier-ignore
!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;r0&&(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");
// SDK initialization
cp('create', cpPropertyId, { baseUrl: cpBaseUrl });
// Authenticate Option:
// Check for login and subscription status
cp('authenticate', function (err, user) {
if (err || (!user.isLoggedIn() && !user.hasValidSubscription())) {
// Load your third party resources for users who are not contentpass users here
//
// Be aware, that this function just checks for contentpass subscription status.
// Therefore code implemented here will be executed immediately and independently
// of the consent status.
//
// To prevent execution for first-time visitors prior to consent, you'd either
// need to check the TCF API as outlined above and therefore wait for the CMP,
// or look for CMP-specific cookies instead.
}
});
```
--------------------------------
### Block Inline Scripts with Usercentrics Data Attributes
Source: https://docs.contentpass.net/docs/onboarding/cmp/usercentrics
This example shows how to block inline scripts that load third-party content until consent is given. Similar to external scripts, the script type is changed to 'text/plain', and a 'data-usercentrics' attribute is added with the specific Data Processing Service name.
```html
```
--------------------------------
### Block YouTube Embeds with CCM19 Loader
Source: https://docs.contentpass.net/docs/onboarding/cmp/ccm19
This example shows how to modify an iframe tag for embedding YouTube videos to block them until user consent is given. It involves replacing the 'src' attribute with 'data-ccm-loader-src' and adding a 'data-ccm-loader-group' attribute. The 'example-group-youtube' should be replaced with the specific group name for YouTube embeds in CCM19. It also recommends using the 'youtube-nocookie.com' domain for enhanced privacy.
```html
```
--------------------------------
### Configure CNAME Record for ContentPass Session Management
Source: https://docs.contentpass.net/docs/onboarding/cmp
This snippet shows how to configure a CNAME record for contentpass session management. It assumes a publisher domain of 'https://www.example.com' and a property ID of '1234abcd'. The CNAME record points to the contentpass service, enabling first-party session management.
```dns
cp.example.com. 300 IN CNAME 1234abcd.12.with.contentpass.net.
```
--------------------------------
### Render ContentPass Consent Layer
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
Triggers the rendering of the Sourcepoint consent layer. It checks the user's authentication status with ContentPass and sets the 'acps' targeting parameter accordingly ('true' for authenticated, 'false' otherwise). The callback `onFullConsent` can be used for post-consent actions like initializing advertising. It also includes a warning about vendor list updates and re-consent.
```javascript
cp('render', {
onFullConsent: function() {
console.log('[CP] onFullConsent');
// Init advertising here
}
})
```
--------------------------------
### Configure amp-consent for Didomi with Contentpass
Source: https://docs.contentpass.net/docs/amp
This snippet shows the configuration for the amp-consent component when integrating Contentpass with Didomi. It includes setting the promptUISrc to the custom Contentpass layer, enabling sandbox for navigation, and configuring client-side settings for Didomi and Contentpass. Replace placeholder values with your actual property details.
```html
```
--------------------------------
### ContentPass Authentication and Sourcepoint Execution
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
Authenticates the user with ContentPass and, based on the authentication result, triggers the Sourcepoint consent messaging. It includes logic to handle cases where Sourcepoint might not be loaded yet, retrying until it's available. It also checks for Sourcepoint's SPA mode and logs relevant information.
```javascript
cp('authenticate', function(err, user) {
if (err || (!user.isLoggedIn() && !user.hasValidSubscription())) {
(function spExecMsg() {
if (window._sp_ && window._sp_.executeMessaging) {
if (!window._sp_.config.isSPA) {
console.warn('[SPCP] Sourcepoint not in SPA mode!');
} else if (window._sp_.version) {
console.log('[SPCP] Sourcepoint already running');
} else {
console.log('[SPCP] Starting Sourcepoint');
window._sp_.executeMessaging();
}
} else {
console.log('[SPCP] Sourcepoint not loaded yet. Retrying.');
setTimeout(spExecMsg, 10);
}
})();
}
});
```
--------------------------------
### Sourcepoint Stub Code Implementation
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
Provides a stub implementation for the TCF API (Transparency and Consent Framework). This code ensures that the `__tcfapi` function is available globally, even if the main CMP (Consent Management Platform) is not yet loaded. It handles basic TCF commands like 'setGdprApplies' and 'ping', and sets up a message listener for communication with the actual CMP.
```javascript
!function () { var e = function () { var e, t = "__tcfapiLocator", a = [], n = window; for (; n;) { try { if (n.frames[t]) { e = n; break } } catch (e) { } if (n === window.top) break; n = n.parent } e || (!function e() { var a = n.document, r = !!n.frames[t]; if (!r) if (a.body) { var i = a.createElement("iframe"); i.style.cssText = "display:none", i.name = t, a.body.appendChild(i) } else setTimeout(e, 5); return !r }(), n.__tcfapi = function () { for (var e, t = arguments.length, n = new Array(t), r = 0; r < t; r++)n[r] = arguments[r]; if (!n.length) return a; if ("setGdprApplies" === n[0]) n.length > 3 && 2 === parseInt(n[1], 10) && "boolean" == typeof n[3] && (e = n[3], "function" == typeof n[2] && n[2]("set", !0)); else if ("ping" === n[0]) { var i = { gdprApplies: e, cmpLoaded: !1, cmpStatus: "stub" }; "function" == typeof n[2] && n[2](i) } else a.push(n) }, n.addEventListener("message", (function (e) { var t = "string" == typeof e.data, a = {}; try { a = t ? JSON.parse(e.data) : e.data } catch (e) { } var n = a.__tcfapiCall; n && window.__tcfapi(n.command, n.version, (function (a, r) { var i = { __tcfapiReturn: { returnValue: a, success: r, callId: n.callId } }; t && (i = JSON.stringify(i)), e.source.postMessage(i, "*") }), n.parameter) }), !1)) }; "undefined" != typeof module ? module.exports = e : e() }();
```
--------------------------------
### Add ContentPass Snippet (JavaScript)
Source: https://docs.contentpass.net/docs/onboarding/cmp/didomi
This snippet initializes ContentPass on your website. Ensure you replace placeholder values for `cpBaseUrl` and `cpPropertyId` with your actual property details. It also includes functions to create, render, and authenticate the ContentPass service, with callbacks for user consent and subscription status.
```javascript
```
--------------------------------
### Sourcepoint Configuration for Multi-Campaign
Source: https://docs.contentpass.net/docs/onboarding/cmp/sourcepoint
This JavaScript object configures Sourcepoint for multi-campaign mode. It includes the account ID, base endpoint, and specific settings like `isSPA` for single-page applications and `gdpr.targetingParams` to control message display. Ensure your `accountId` is correctly set.
```javascript
window._sp_ = {
config: {
accountId: {{accountId}},
baseEndpoint: 'https://cdn.privacy-mgmt.com',
isSPA: true,
gdpr: {
targetingParams: {
acps: 'false'
},
}
}
};
```
--------------------------------
### Load Advertising and Authenticate User with ContentPass (JavaScript)
Source: https://docs.contentpass.net/docs/onboarding/cmp/onetrust
This snippet demonstrates how to load advertising and authenticate a user with ContentPass. The `cp('authenticate', callback)` function checks the user's login state and subscription validity, allowing for layout updates based on their status. Error handling is included.
```javascript
cp('authenticate', function (error, user) {
if (error) {
// Error handling depending on use case
return;
}
if (user.isLoggedIn() && user.hasValidSubscription()) {
// User has valid subscription
} else {
// User has no valid subscription
}
});
```