Add Custom Scripts
Load your own scripts and other vendors' tags on every page of your developer portal, and pass them the portal's events.
portal.scripts in src/apimatic.json lists scripts for the portal to load on every page, such as a chat widget, a consent banner, or another analytics tool. A script can also get the portal's events, such as page views and searches, from window.apimatic.analytics.subscribe().
Every script you list loads for every reader.
- It can read everything on the page. That includes what readers type into the API playground, such as API keys and tokens, and what the playground keeps in the browser's session storage, such as the token from an OAuth 2.0 sign-in. List only scripts you trust.
- What an address serves can change without a rebuild. A script listed by its address runs whatever the address serves when a page loads. A change by its vendor, or by anyone who takes over the address, reaches your published portal at once. A file in
src/staticchanges only when you rebuild, though code it loads from elsewhere can still change. - The portal doesn't ask readers for consent. Implementing consent is your responsibility, under the laws and regulations that apply to your portal.
List your scripts
{
"portal": {
"scripts": [
{ "src": "static/js/consent.js", "category": "necessary" },
{ "src": "https://cdn.example.com/chat.js", "category": "functional" },
{ "src": "https://cdn.example.com/analytics.js", "category": "analytics" }
]
}
}An entry has two properties:
| Property | Required | What it is |
|---|---|---|
src | Yes | The script to load: an address that starts with https://, or a file under src/static. |
category | Yes | What the script is for: necessary, functional, analytics, or marketing. See Categories. |
The CLI refuses any other property, such as attributes, as an unknown setting. For a vendor's inline snippet, or a tag that needs attributes, see Add a vendor's snippet.
Where a script comes from
- An address must start with
https://and a host, and contain no spaces. An address that starts withhttp://is refused. - A file lives under
src/static, and you write its path relative tosrc, for examplestatic/js/widget.js. See static paths. The portal loads it from its own site:/js/widget.js, or/docs/js/widget.jswhenportal.site.urlhas the path/docs.
A listed file must exist. If it doesn't, apimatic portal generate and apimatic portal serve stop with an error that names the setting, such as portal.scripts[1].src. If only the letter case of the name differs, the error also shows how the file is spelled on disk.
Categories
A category says what a script is for. The four are the groups that consent tools ask readers about, such as Cookiebot's necessary, preferences, statistics and marketing, or OneTrust's strictly necessary, functional, performance and targeting.
| Category | What belongs in it | For example | Loads with --no-analytics |
|---|---|---|---|
necessary | What the portal needs to work, or the law requires. | Your consent tool | Yes |
functional | A feature a reader sees or uses, which may remember their choices. | A chat widget, a feedback form, a status banner | Yes |
analytics | Anything that measures how readers use the portal. | An analytics tool, a session recorder, an A/B testing tool | No |
marketing | Anything that serves or measures advertising, or follows readers across sites. | An advertising pixel, a retargeting tag | No |
A script that does more than one of these gets the category lowest in the table that applies. A feedback widget that also records sessions is analytics, and a chat widget that also tracks readers for advertising is marketing.
A category decides one thing: whether --no-analytics leaves the script out. It doesn't make a script wait for the reader's consent. Every entry needs a category, and the CLI stops with an error when one is missing.
How scripts load
- The portal adds each script to the page's
<head>, after the Google tags fromportal.analytics. - Scripts run in the order you list them, so a script can rely on one listed before it.
- Each script runs once for each page load. Moving between pages inside the portal doesn't run it again. An address listed twice loads once.
- A script that is already in the page's
<head>when the portal starts, such as one your host adds to every page, isn't added again. The portal matches it by itssrcas written. - Each script is loaded as a classic script, not as a module.
- The portal adds the scripts from its own code once the page is ready, so they aren't in the page's HTML source.
- A script can add elements to the page, such as a link in the header. The header and sidebar stay as a reader moves between pages, and so does anything a script adds to them. Something added inside a page's content may stay on the next page or disappear.
- No listed script loads on
/oauth/callback, whatever its category. That's the page an OAuth 2.0 provider sends the reader back to after a sign-in in the API playground. See Sign-in responses.
Leave scripts out of previews and staging builds
apimatic portal serve --no-analytics
apimatic portal generate --no-analyticsWith --no-analytics, the portal:
- Leaves out the tags set in
portal.analytics. - Leaves out every
analyticsandmarketingscript. - Sends no events to the scripts that stay, or to
window.dataLayer.
necessary and functional scripts still load. They can still call window.apimatic.analytics.subscribe() without an error, but the portal never calls their callback.
The flag doesn't remove files: everything in src/static is still copied to the built portal, but no page loads a left-out script's file. That file must still exist, or the CLI stops with an error.
For every flag, see portal generate and portal serve in the CLI Reference.
Get the portal's events
Every portal has window.apimatic.analytics.subscribe(callback), which passes a script the events the portal reports: page views, searches, code copies, and the rest. It's there whether or not you set a Google tag or list a script. With --no-analytics, it delivers no events.
This file forwards every event to an analytics tool:
window.apimatic.analytics.subscribe((event) => {
if (event.name === 'docs_page_view') {
tracker.page({ title: event.params.page_title, url: event.params.page_location });
} else {
tracker.track(event.name, event.params);
}
});tracker stands for your analytics tool's own object. Replace the two calls with the ones your tool documents. Then list the file after the tool's own script, so that the tool's script runs first:
{
"portal": {
"scripts": [
{ "src": "https://cdn.example.com/tracker.js", "category": "analytics" },
{ "src": "static/js/forward-events.js", "category": "analytics" }
]
}
}What an event holds
{
name: 'docs_code_copy',
params: { code_language: 'python', page_location: 'https://docs.acme.com/guides/quickstart' },
time: 1763280000000,
version: 1
}| Key | What it holds |
|---|---|
name | The event's name, such as docs_page_view. |
params | The event's parameters, with page_location among them. See Event parameters. |
time | When the event was reported, in milliseconds since the epoch. |
version | 1, the version of this format. |
The event and its params are frozen, so a callback can't change them.
How events are delivered
- The callback gets every event reported since the page loaded, in order, and then each new event as it's reported. A script that subscribes late misses nothing.
- Use
event.time, not your own clock, for when an event happened. An earlier event reaches a late subscriber some time after it was reported. - Earlier events arrive just after
subscribe()returns, never inside the call. subscribe()returns a function that stops delivery.- A callback that throws shows its error in the browser's console. It stops no other callback and no later event.
subscribe()throws aTypeErrorwhen you pass it something that isn't a function.- The portal keeps every event in memory for as long as the page stays loaded, with no upper limit.
To act on one event and then stop, call the function that subscribe() returns:
(() => {
const stop = window.apimatic.analytics.subscribe((event) => {
if (event.name !== 'docs_page_view') return;
console.log('First page:', event.params.page_location);
stop();
});
})();The wrapping function keeps stop private to this file. Listed scripts share one global scope, so two files that each declare a stop of their own at the top level would clash.
Scripts loaded another way
window.apimatic.analytics is in place before the portal adds any tag or listed script. A script loaded another way, such as one your host adds to the page, can run before the portal's code and not find it. List that script in portal.scripts instead.
Don't define window.apimatic.analytics yourself; the portal replaces it when it starts. If your host already has its own object at window.apimatic, the portal keeps that object and adds analytics to it.
Add a vendor's snippet
Many vendors give you an inline snippet rather than an address. Save the snippet's code, without its <script> tags, as a file under src/static, and list the file.
For a vendor whose tag reads a data- attribute from its own script tag, list a small file that creates the tag:
(() => {
const tag = document.createElement('script');
tag.src = 'https://cdn.example.com/tracker.js';
tag.dataset.site = 'ABC123';
document.head.append(tag);
})();{
"portal": {
"scripts": [
{ "src": "static/js/vendor-tag.js", "category": "analytics" }
]
}
}tag.dataset.site sets data-site="ABC123" on the tag. The file's category covers the tag it adds: --no-analytics leaves the file out, and the tag with it.
Limits
- A script that fails to load doesn't affect the others: they still run.
- A script whose host accepts the connection but never answers delays every listed script after it, until its request ends. On a built portal, the page's
loadevent can be delayed too, and so can anything that waits for it, such as Google Tag Manager's Window Loaded trigger. The page, the Google tags, and the portal's events aren't affected. A script listed last delays no other listed script. - Content Security Policy. If your portal's host sets one, its
script-srcmust allow the host of each listed address, and of any tag a listed file adds.