Skip to content

Commit 16b8c4f

Browse files
Add Google Analytics across the documentation website
# TLDR; Load Google Analytics measurement ID `G-PGDS00DBRX` from the shared website head on every page. # Details - Add the async Google tag loader and its standard initialization to the shared layout. - Allow only the exact analytics script URL through the site audit while preserving the 2,500-byte CSS budget and restrictions on other external scripts. - Stub Google requests in browser tests so automated runs do not generate analytics visits. # How Do The Tests Prove The Changes Work? Shared browser assertions verify one async tag and one ordered initialization/configuration sequence on every tested HTML page. Focused tests cover English and Chinese page families, navigation, and reloads. Guard tests reject altered script URLs and preserve CSS restrictions. Validation: 108 browser tests and 26 supporting tests pass with no failures or skips. The build audits all 110 pages; shipped CSS remains 2,491 bytes.
1 parent f62b1ba commit 16b8c4f

5 files changed

Lines changed: 142 additions & 2 deletions

File tree

‎Website/scripts/check-site.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { parse as parseHtml } from 'parse5';
66
import { parse as parseJavaScript } from 'acorn';
77

88
export const CSS_BUDGET = 2500;
9+
const AUTHORIZED_GOOGLE_TAG = 'https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX';
910

1011
async function filesUnder(directory) {
1112
const entries = await readdir(directory, { withFileTypes: true });
@@ -143,7 +144,7 @@ export async function auditSite(directory, options = {}) {
143144
}
144145
if (node.tagName === 'script' && attribute(node, 'type') !== 'application/ld+json') {
145146
const src = attribute(node, 'src');
146-
if (src && new URL(src, url).origin !== configured.origin) errors.push(`${relative}: external JavaScript could inject unbudgeted styles`);
147+
if (src && new URL(src, url).origin !== configured.origin && src !== AUTHORIZED_GOOGLE_TAG) errors.push(`${relative}: external JavaScript could inject unbudgeted styles`);
147148
if (!src && content(node).trim()) errors.push(...cssInjectionErrors(content(node), relative));
148149
}
149150
if (node.tagName === 'link' && attribute(node, 'hreflang')) {

‎Website/src/_includes/layouts/base.njk‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
<!doctype html>
22
<html lang="{{ lang or 'en' }}">
33
<head>
4+
<!-- Google tag (gtag.js) -->
5+
<script async src="https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX"></script>
6+
<script>
7+
window.dataLayer = window.dataLayer || [];
8+
function gtag(){dataLayer.push(arguments);}
9+
gtag('js', new Date());
10+
11+
gtag('config', 'G-PGDS00DBRX');
12+
</script>
413
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
514
<title>{{ title }} · {{ page.url | section | upper }} · RestClient.Net</title>
615
<meta name="description" content="{{ description or excerpt or site.description }}">

‎Website/tests-node/site-guards.test.js‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,63 @@ test('external scripts cannot outsource hidden CSS', async t => {
102102
assert.match((await site.run()).errors.join('\n'), /external JavaScript/);
103103
});
104104

105+
test('the exact user-authorized Google tag works on root and prefixed deployments', async t => {
106+
for (const prefix of ['/', '/RestClient.Net/']) {
107+
const site = await fixture(t, { prefix });
108+
await site.write('index.html', site.html('<h1>Docs</h1>', `
109+
<script async src="https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX"></script>
110+
<script>
111+
window.dataLayer = window.dataLayer || [];
112+
function gtag(){dataLayer.push(arguments);}
113+
gtag('js', new Date());
114+
gtag('config', 'G-PGDS00DBRX');
115+
</script>`));
116+
const report = await site.run();
117+
assert.deepEqual(report.errors, []);
118+
assert.equal(report.cssBytes, Buffer.byteLength('body{color:#123}', 'utf8'));
119+
assert.equal(report.pageCount, 1);
120+
}
121+
});
122+
123+
test('Google tag exception rejects every altered origin, path, measurement ID, and query', async t => {
124+
const site = await fixture(t);
125+
for (const src of [
126+
'http://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX',
127+
'//www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX',
128+
'https://googletagmanager.com/gtag/js?id=G-PGDS00DBRX',
129+
'https://www.googletagmanager.com.evil.test/gtag/js?id=G-PGDS00DBRX',
130+
'https://www.googletagmanager.com@evil.test/gtag/js?id=G-PGDS00DBRX',
131+
'https://www.googletagmanager.com:444/gtag/js?id=G-PGDS00DBRX',
132+
'https://www.googletagmanager.com/gtm.js?id=G-PGDS00DBRX',
133+
'https://www.googletagmanager.com/gtag/js/extra?id=G-PGDS00DBRX',
134+
'https://www.googletagmanager.com/gtag/js?id=G-OTHER',
135+
'https://www.googletagmanager.com/gtag/js',
136+
'https://www.googletagmanager.com/gtag/js?other=G-PGDS00DBRX',
137+
'https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX&extra=1',
138+
'https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX&id=G-OTHER',
139+
'https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX#extra',
140+
'https://www.googletagmanager.com/gtag/js?id=%47-PGDS00DBRX',
141+
]) {
142+
await site.write('index.html', site.html('<h1>Docs</h1>', `<script async src="${src}"></script>`));
143+
const report = await site.run();
144+
assert.ok(report.errors.some(error => error.includes('external JavaScript')), src);
145+
assert.equal(report.cssBytes, Buffer.byteLength('body{color:#123}', 'utf8'));
146+
}
147+
});
148+
149+
test('authorized Google tag does not exempt any CSS or other external scripts', async t => {
150+
const site = await fixture(t, { stylesheet: ' '.repeat(CSS_BUDGET + 1) });
151+
await site.write('index.html', site.html('<h1 style="color:red">Docs</h1>', `
152+
<script async src="https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX"></script>
153+
<script src="https://cdn.test/unapproved.js"></script>
154+
<link rel="stylesheet" href="https://www.googletagmanager.com/gtag/js?id=G-PGDS00DBRX">`));
155+
const errors = (await site.run()).errors.join('\n');
156+
assert.match(errors, /CSS budget exceeded/);
157+
assert.match(errors, /inline CSS bypasses/);
158+
assert.match(errors, /external or embedded stylesheet/);
159+
assert.match(errors, /external JavaScript/);
160+
});
161+
105162
test('SVG assets cannot conceal extra CSS outside the shared budget', async t => {
106163
const site = await fixture(t);
107164
for (const svg of ['<svg><style>text{font-size:99px}</style></svg>', '<svg><text style="font-size:99px">Hello</text></svg>']) {

‎Website/tests/analytics.test.js‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { test, expect, expectAnalytics, analyticsScriptUrl } from './fixtures.js';
2+
3+
for (const [language, routes] of [
4+
['English', ['/', '/docs/basic-usage/', '/blog/introducing-restclient/', '/api/reference/restclient-net-httpclientextensions/', '/examples/']],
5+
['Chinese', ['/zh/', '/zh/docs/basic-usage/', '/zh/blog/introducing-restclient/', '/zh/api/httpclient-extensions/', '/zh/examples/']],
6+
]) {
7+
test(`${language} page families queue the provided Google Analytics configuration once`, async ({ page }) => {
8+
const requests = [];
9+
page.on('request', request => { if (request.url() === analyticsScriptUrl) requests.push(request.url()); });
10+
for (const route of routes) {
11+
const response = await page.goto(route);
12+
expect(response?.status()).toBe(200);
13+
await expect(page.locator('html')).toHaveAttribute('lang', language === 'English' ? 'en' : 'zh');
14+
await expectAnalytics(page);
15+
}
16+
expect(requests).toHaveLength(routes.length);
17+
});
18+
}
19+
20+
test('link navigation and reload start one fresh analytics queue per document', async ({ page }) => {
21+
await page.goto('/');
22+
await expectAnalytics(page);
23+
await page.evaluate(() => { window.__analyticsTestDocument = 'initial'; });
24+
25+
await page.getByRole('navigation', { name: 'Main navigation', exact: true }).getByRole('link', { name: 'Docs', exact: true }).click();
26+
await expect(page).toHaveURL(/\/docs\/$/);
27+
expect(await page.evaluate(() => window.__analyticsTestDocument)).toBeUndefined();
28+
await expectAnalytics(page);
29+
await page.evaluate(() => { window.__analyticsTestDocument = 'before-reload'; });
30+
31+
const response = await page.reload();
32+
expect(response?.status()).toBe(200);
33+
expect(await page.evaluate(() => window.__analyticsTestDocument)).toBeUndefined();
34+
await expectAnalytics(page);
35+
36+
await page.getByRole('navigation', { name: 'Main navigation', exact: true }).getByRole('link', { name: 'API', exact: true }).click();
37+
await expect(page).toHaveURL(/\/api\/$/);
38+
await expectAnalytics(page);
39+
});

‎Website/tests/fixtures.js‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,47 @@
11
import { test as base, expect } from '@playwright/test';
22

3+
export const analyticsId = 'G-PGDS00DBRX';
4+
export const analyticsScriptUrl = `https://www.googletagmanager.com/gtag/js?id=${analyticsId}`;
5+
6+
export async function expectAnalytics(page) {
7+
const loader = page.locator(`head script[src="${analyticsScriptUrl}"]`);
8+
await expect(loader, 'Each HTML page loads the requested Google tag once in its head').toHaveCount(1);
9+
await expect(loader).toHaveAttribute('async', '');
10+
await expect(page.locator('script[src*="googletagmanager.com"]')).toHaveCount(1);
11+
const queue = await page.evaluate(() => {
12+
const calls = Array.isArray(window.dataLayer) ? window.dataLayer.map(entry => Array.from(entry)) : [];
13+
return {
14+
commands: calls.map(call => call[0]),
15+
initializationHasDate: calls[0]?.[1] instanceof Date,
16+
initializedAt: calls[0]?.[1] instanceof Date ? calls[0][1].getTime() : null,
17+
config: calls[1],
18+
gtagType: typeof window.gtag,
19+
};
20+
});
21+
expect(queue.commands, 'Queue initializes before configuring, with no duplicate tag setup').toEqual(['js', 'config']);
22+
expect(queue.initializationHasDate).toBe(true);
23+
expect(Number.isFinite(queue.initializedAt)).toBe(true);
24+
expect(queue.initializedAt).toBeGreaterThan(0);
25+
expect(queue.config).toEqual(['config', analyticsId]);
26+
expect(queue.gtagType).toBe('function');
27+
}
28+
329
export const test = base.extend({
4-
browserHealth: [async ({ page }, use) => {
30+
browserHealth: [async ({ page, context }, use) => {
31+
// Exercise the real inline initialization without loading Google code or sending visits.
32+
// Only this exact, authorized URL is intercepted; browser failures stay strict.
33+
await context.route(analyticsScriptUrl, route => route.fulfill({
34+
status: 200,
35+
contentType: 'application/javascript',
36+
body: '/* Google tag intentionally stubbed in browser tests. */',
37+
}));
538
const errors = [];
639
page.on('pageerror', error => errors.push(error.message));
740
page.on('console', message => { if (message.type() === 'error') errors.push(message.text()); });
841
await use();
942
expect(errors, 'Every interaction must finish without browser errors').toEqual([]);
1043
if (await page.locator('meta[name="viewport"]').count()) {
44+
await expectAnalytics(page);
1145
await expect(page.locator('main')).toHaveCount(1);
1246
await expect(page.locator('h1')).toHaveCount(1);
1347
await expect(page.locator('html')).toHaveAttribute('lang', /^(en|zh)$/);

0 commit comments

Comments
 (0)