> For the complete documentation index, see [llms.txt](https://docs.mediarithmics.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mediarithmics.io/setup-and-monitor/plan-and-integrate/set-up-advanced-features/contextual-targeting.md).

# Contextual targeting

Set up the contextual targeting module: the schema update and event rule every customer needs, and the snippet that activates targeting lists.

## Your goal

Prepare your environment so that contextual targeting can analyse your content and, if you need it, activate targeting lists on your pages.

## Expected outcome

Your schema carries the contextual fields, the **Contextual Targeting Extractor** event rule runs on your channels, and - if you activate targeting lists - the contextual snippet is deployed on your pages.

## Prerequisites

The contextual module enabled for your organisation. It is not enabled by default: get in touch with your Account Manager. What contextual targeting is, and its solutions, are described in [Contextual reference](https://docs.mediarithmics.io/audience-and-activation/target-contextually/contextual-reference.md).

## General setup (mandatory)

Every customer using contextual targeting needs this setup, whether or not they activate targeting lists.

{% hint style="warning" %}
Follow these steps **in order**: schema update, then event rule configuration.
{% endhint %}

{% stepper %}
{% step %}

#### Update the schema

{% hint style="warning" %}
Contextual targeting currently only works with the **standard schema**. Contact your Account Manager if you do not have a `UserEvent` type in your schema.
{% endhint %}

For both solutions, add this line to the `UserEvent` type in your runtime schema:

```
contextual_key:String @TreeIndex(index:"USER_INDEX")
```

and make sure the `ts` field in `UserEvent` is indexed:

```
ts:Timestamp! @TreeIndex(index:"USER_INDEX")
```

{% hint style="warning" %}
The `$url` attribute must be populated with a proper URL for the `contextual_key` to be extracted. The key is the URL without protocol and without query strings.
{% endhint %}

For **semantic** targeting, and in particular to create audience segments from semantic information, add:

```
semantic_tagging:[SemanticTagging] @Property(path:"$properties.$semantic_tagging")
targeting_list_ids:[String] @TreeIndex(index:"USER_INDEX") @ReferenceTable(type:"CORE_OBJECT", model_type:"CONTEXTUAL_TARGETING_LISTS") @Property(path:"$properties.$targeting_list_ids")
```

along with the types they refer to:

```
type SemanticTagging  {
   provider_id:String @Property(path:"$provider_id") @TreeIndex(index:"USER_INDEX")
   provider_version:String @Property(path:"$provider_version") @TreeIndex(index:"USER_INDEX")

   entities:[SemanticEntity] @Property(path:"$entities")
   iab_categories:[SemanticIABCategory] @Property(path:"$iab_categories")
}

type SemanticEntity  {
   entity_id:String @Property(path:"$entity_id") @TreeIndex(index:"USER_INDEX")
   name:String @Property(path:"$name") @TreeIndex(index:"USER_INDEX")
   type:String @Property(path:"$type")
   wikidata_id:String @Property(path:"$wikidata_id")
}

type SemanticIABCategory  {
   category_id:String @TreeIndex(index:"USER_INDEX") @Property(path:"$category_id")
   name:String @TreeIndex(index:"USER_INDEX") @Property(path:"$name")
}
```

{% hint style="info" %}
Add `@EdgeAvailability` on `semantic_tagging` and `targeting_list_ids` if you want to use those characteristics in [Edge segments](https://docs.mediarithmics.io/audience-and-activation/build-your-audiences/segment-reference/segment-types/edge-segment.md).
{% endhint %}

Schema work in general is documented in [Design your data model & schema](https://docs.mediarithmics.io/setup-and-monitor/collect-and-manage-your-data/design-your-data-model-and-schema.md).
{% endstep %}

{% step %}

#### Add the Contextual Targeting Extractor event rule

Add the **Contextual Targeting Extractor** event rule to the channels where you want to use contextual targeting. The event rule mechanism itself is documented in [Event rules](https://docs.mediarithmics.io/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/event-rules.md); what this particular rule does is:

* **Specify which JavaScript tag collects URLs and hits.** Either the **user event tag**, which uses the URL explicitly passed in the event and requires the tracking snippet, or the **contextual targeting tag**, which captures the page URL from the browser automatically and requires the contextual snippet.
* **Calculate and add the contextual key** to the event. Automatic once the rule is added.
* **Add the extracted semantic information** to the event. Required if you want audience segments based on semantic information - tick **Tag event with semantic extract**.
* **Blacklist URLs**, individually or by pattern. No semantic extraction and no targeting is performed on them.

{% hint style="danger" %}
**Tag event with semantic extract is not retroactive.** Events ingested before the option is switched on are not tagged with entities or IAB categories, and are therefore not targetable through those criteria. The same applies to targeting list IDs and the **Use for Audience segments** option on a list.
{% endhint %}
{% endstep %}

{% step %}

#### Blacklist URLs

One entry per line, in each list.

{% tabs %}
{% tab title="Blacklist URL" %}
One URL per line. **None of them may include the protocol** (`http://`, `https://`):

```
www.mediarithmics.io/homepage
actu.mediarithmics.io/
mediarithmics.io/actu
```

{% endtab %}

{% tab title="Blacklist Regexp" %}
One expression per line. Only `*` is authorised, and `*` is automatically applied before and after the input expression.

```
mediarithmics*.io/homepage
```

blacklists:

* `www.mediarithmics.io/homepage`
* `mediarithmicsTEST.io/homepage`
* `mediarithmics*io/homepage/page`
  {% endtab %}
  {% endtabs %}

{% hint style="info" %}
On a news site, blacklist the pages that **list** articles - usually themed index pages such as "politics" - which are refreshed frequently and whose semantic content is therefore unstable.
{% endhint %}
{% endstep %}
{% endstepper %}

## Activation setup (optional)

Needed only to activate targeting lists.

{% tabs %}
{% tab title="Website" %}
{% stepper %}
{% step %}

#### Deploy the contextual snippet

For website activation, deploy the contextual targeting snippet on every page where contextual targeting activation should happen. The snippet is made of a **configuration** you fill in with your site token and a snippet name, and a **technical part** that asynchronously loads the contextual targeting tag and must not be edited.

The site token for each channel is found in **Settings > Datamart > Channel**.

{% hint style="info" %}
Common integration routes: through a universal tag container such as Google Tag Manager, where the snippet is copied once into a new tag; or by inserting it into a general-purpose template used across all pages, such as a header template.

The snippet should go in the `<head>` of the page. Its code is non-blocking and does not affect page rendering time.
{% endhint %}

The tag loaded by the snippet can also capture new URLs and their hits, which is why it can serve as the collection route as well as the activation route.
{% endstep %}

{% step %}

#### Handle single-page applications

Optional, depending on your site.

In a single-page application, call the following function whenever the URL changes, on every page where contextual targeting should be performed:

```javascript
ctMics.forceSetTargeting() // replace "ctMics" by the snippetName you used
```

The call extracts the current URL, looks up the associated targeting lists, and synchronises their IDs with the configured activation platforms.

{% hint style="warning" %}
Call it as early as possible, so the targeting list IDs are calculated **before the auction runs**. A late call produces no error - it produces an auction with no contextual targeting.
{% endhint %}
{% endstep %}
{% endstepper %}
{% endtab %}

{% tab title="Mobile app" %}
{% hint style="warning" %}
For mobile app content to be eligible for activation, it must be linked to a URL that can be analysed. Contextual targeting therefore works on applications that mirror a website: the semantic analysis and the targeting lists are built on the website, and the results are made available to an app that calls the API with a known URL.
{% endhint %}

{% stepper %}
{% step %}

#### Integrate the API

Integrate the API that fetches the targeting lists associated with a given URL. The response carries an array of targeting list IDs. Signature authentication is documented in [Manage API access](https://docs.mediarithmics.io/setup-and-monitor/manage-the-platform/manage-api-access.md).
{% endstep %}

{% step %}

#### Send the IDs to the activation platform

Send those IDs to the activation platform you work with, following that platform's own documentation.
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

### How the tag behaves

{% stepper %}
{% step %}

#### It identifies the URL

The contextual targeting tag identifies the URL browsed by an anonymous user.
{% endstep %}

{% step %}

#### It resolves the lists

It determines which targeting lists are associated with that URL.
{% endstep %}

{% step %}

#### It performs key-value targeting

It proceeds to key/value targeting with the configured activation platforms.
{% endstep %}
{% endstepper %}

## Related pages

<table data-view="cards" data-search="false"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Contextual reference</strong></td><td>What contextual targeting is, and the solutions it offers.</td><td><a href="https://docs.mediarithmics.io/audience-and-activation/target-contextually/contextual-reference.md">Contextual reference</a></td></tr><tr><td><strong>Contextual activation</strong></td><td>Activate a targeting list once this setup is done.</td><td><a href="https://docs.mediarithmics.io/audience-and-activation/target-contextually/contextual-reference/contextual-activation.md">Contextual activation</a></td></tr><tr><td><strong>Event rules</strong></td><td>How event rules work on a channel.</td><td><a href="https://docs.mediarithmics.io/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/event-rules.md">Event rules</a></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.mediarithmics.io/setup-and-monitor/plan-and-integrate/set-up-advanced-features/contextual-targeting.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
