v1.1See what changed

Implementation guide

Everything you need to add browser integrity monitoring to your exam or quiz platform: one script tag on the exam page, one endpoint on your server.

New in v1.1: field changes and page changes are no longer penalised, one session and score per attempt across quiz pages, seq on every event, time-away measurement, and four new signals (multi_screen, automation_flag, drop_attempt, insert_burst). Drop-in upgrade: replace the file. See the changelog.

Quick start

Two steps, however you work: get the file and add the tag — then give your server a place to receive events. Pick whichever path fits you.

Path A — ask your AI agent (recommended)

Using Claude, Copilot, Cursor or any coding agent? Paste this prompt and it will wire everything into your stack, including the collector:

Prompt for your coding agent
Add tinyproctor.js exam integrity monitoring to my project:
1. Fetch https://tanzir71.github.io/tinyproctorjs/tinyproctor.min.js
   and add it to my static assets.
2. Add its script tag to my exam/quiz page with data-endpoint pointing
   at a new /collect endpoint, plus my real exam and attempt IDs.
3. Implement /collect for my backend following
   https://tanzir71.github.io/tinyproctorjs/llms.txt — store events with
   attemptId, violationKey and integrityScore so I can review attempts.

The full machine-readable integration contract lives at /llms.txt — payload schema, config reference, and validation rules in one plain-text file any agent can read.

Path B — one command

The library is a single static file. Download it straight into your project's assets:

Terminal
curl -LO https://tanzir71.github.io/tinyproctorjs/tinyproctor.min.js

Want the repo with the demo server and test suite too? git clone https://github.com/tanzir71/tinyproctorjs

Path C — manual

1. Host the script. Serve tinyproctor.min.js (under 7 KB gzipped) from your own domain. No CDN, no third-party calls.

2. Embed it on the exam page.

exam-page.html
<script
  src="/js/tinyproctor.min.js"
  data-tinyproctor
  data-endpoint="https://your-domain.com/collect.php"
  data-exam-id="FINAL_2026_06"
  data-attempt-id="ATTEMPT_12345"
  data-candidate-label="student_42">
</script>

3. Receive events. The script batches events and POSTs JSON to your data-endpoint. A complete collector is ~30 lines — copy-paste the PHP or Node.js examples below.

Monitoring starts automatically as soon as the script loads — no init call needed. On a multi-page quiz, put the same tag with the same data-attempt-id on every page: v1.1 keeps one session and one score per attempt across pages.

What it detects

Violation keyTriggerDefault weight
tab_hiddenCandidate switches to another tab or minimizes the browser (visibilitychange)10
window_blurBrowser window loses focus — e.g. clicking another app (blur). Moving between form fields does not count.5
fullscreen_exitCandidate leaves fullscreen mode (fullscreenchange)25
devtools_keyF12, Ctrl/Cmd+Shift+I/J/C, Cmd+Alt+I key combos20
devtools_resizeHeuristic: large gap between outer and inner window size — DevTools, but also docked side panels and AI sidebars. Checked on resize and once at start (desktop)15
copy_attemptCopy event anywhere on the page10
cut_attemptCut event anywhere on the page10
paste_attemptPaste event anywhere on the page15
context_menuRight-click / context menu opened5
print_attemptCtrl/Cmd+P or the browser's beforeprint event10
page_idleNo mouse/keyboard/scroll/touch activity for idleMs (default 60s)5
drop_attempt v1.1Text dragged and dropped into the page (bypasses paste events). File drops are ignored15
insert_burst v1.140+ characters inserted in one input event — the pattern of AI agent browsers, auto-typers and text expanders. Records the length, never the text15
multi_screen v1.1screen.isExtended is true at start or after a display change (Chromium; no permission prompt)10
automation_flag v1.1navigator.webdriver is true (WebDriver-controlled browser). Easy to spoof: false proves nothing25
custom / any keyYour own logic via instance.markViolation(key, data)—

Every signal can be disabled individually. Clipboard and context-menu actions can also be blocked (not just detected) with data-block-clipboard and data-block-contextmenu.

A heartbeat event fires every 30 seconds (configurable) so your backend can detect dropped sessions and confirm the monitor stayed alive for the full attempt.

Tab switches: switching tabs usually fires both tab_hidden and window_blur (15 points). Set data-blur-dedupe-ms="500" to count it once. Returning to the tab sends an info event with awayMs, so reviewers can tell a 2-second glance from a 4-minute absence.

Page changes: moving to the next page of a quiz or reloading is not a tab switch. It is sent as an info event with { unload: true }, and the next page's session event carries gapMs, the time between the two pages.

Configuration reference

All options are set as data-* attributes on the script tag (or as a config object via TinyProctor.init()).

AttributeDefaultDescription
data-endpoint—Required for reporting. Collector URL (absolute or relative). Without it, events are kept locally only.
data-exam-id""Identifier for the exam, included in every event.
data-attempt-idautoStrongly recommended. Per-attempt ID from your exam system. Auto-generated if omitted. Setting it also enables cross-page sessions.
data-candidate-label""Pseudonymous candidate label. Avoid raw PII; use your system's internal ID.
data-silenttruefalse shows a small read-only badge with live score and violation count.
data-heartbeat-ms30000Heartbeat interval (clamped 5s–10min).
data-devtoolstrueEnable DevTools heuristics (keys + resize).
data-clipboardtrueDetect copy/cut/paste.
data-block-clipboardfalseAlso prevent copy/cut/paste and text drops (calls preventDefault).
data-contextmenutrueDetect right-click.
data-block-contextmenufalseAlso block the context menu.
data-printtrueDetect print attempts (Ctrl/Cmd+P, beforeprint).
data-idletrueDetect inactivity.
data-idle-ms60000Inactivity threshold (clamped 10s–30min).
data-screenstrueDetect a second screen (multi_screen).
data-automationtrueDetect navigator.webdriver (automation_flag).
data-inserttrueDetect bulk text inserts (insert_burst).
data-insert-chars40Characters inserted in one event that count as insert_burst (5–100000). Raise it if candidates use dictation software.
data-blur-dedupe-ms0Drop a window_blur that comes with a tab_hidden within this many ms (0–5000). 0 keeps v1.0 scoring.
data-persisttrue*Keep one session per attempt across page loads in sessionStorage. *Only when data-attempt-id is set.
data-batch-bytes49152Max bytes per POST (4096–61440); keepalive requests share a 64 KiB budget.
data-weightsdefaultsJSON object overriding violation weights, e.g. '{"tab_hidden":20}'. Unlisted keys keep defaults.
data-flush-ms900Batch flush interval (150–5000ms).
data-batch-max20Max events per POST (1–100).
data-queue-max250Max locally queued events before oldest are dropped (50–5000).
data-credentialsomitFetch credentials mode: omit | same-origin | include.
data-formatjsontext sends the JSON as text/plain (no CORS preflight); form sends payload=<urlencoded json> for legacy PHP backends.
data-devtools-resize-threshold160Pixel delta that triggers the resize heuristic (60–600).
data-devtools-resize-cooldown-ms10000Cooldown between resize violations (1–60s).
data-autoinittruefalse disables auto-start; call TinyProctor.init() yourself.

Integrity scoring

The score starts at 100 and decreases with each weighted violation, clamped to [0, 100]:

score = 100 − Σ ( weight[key] × count[key] )

Weights are fully configurable. A practical reading of the default scale:

  • 80–100 — clean or near-clean session
  • 50–79 — worth a human review
  • 0–49 — multiple or severe flags; investigate
Important: the score is a triage signal, not proof of cheating. A dropped window focus can be a notification popup; a paste can be legitimate. Always pair automated flags with human review before any academic-integrity decision.

JavaScript API

For programmatic control, disable auto-init and configure in JS:

exam-page.html
<script src="/js/tinyproctor.min.js" data-tinyproctor data-autoinit="false"></script>
<script>
  var proctor = TinyProctor.init({
    endpoint: '/collect',
    examId: 'FINAL_2026_06',
    attemptId: attempt.id,
    candidateLabel: user.internalId,
    weights: { fullscreen_exit: 30 },
    onViolation: function (key, data, state) {
      // e.g. warn the candidate in your own UI
      if (state.integrityScore < 50) showWarningBanner()
    },
    onEvent: function (payload) {
      // every event (heartbeats included), before it is sent
    }
  })

  // Enforce fullscreen at exam start (must be called from a user gesture)
  startButton.addEventListener('click', function () {
    proctor.requestFullscreen()
  })
</script>
MethodDescription
TinyProctor.init(config?)Create + start the singleton instance. Returns the existing instance if already initialized.
TinyProctor.get()Return the current instance (or null).
TinyProctor.destroy(clearSession?)Stop monitoring, flush the queue, remove listeners and badge, and allow re-init. Pass true after submit to also forget the saved cross-page session.
TinyProctor.versionLibrary version string.
instance.getState()Snapshot: score, counts, recent violations, queue stats, focus/fullscreen/idle state, plus seq, awayMs (total time away) and resumed.
instance.getConfig()Resolved configuration.
instance.flush()Force-send queued events immediately.
instance.stop()Stop monitoring and flush.
instance.requestFullscreen(el?)Request fullscreen (call from a user gesture).
instance.exitFullscreen()Exit fullscreen.
instance.markViolation(key, data?)Record a custom violation with your own key and payload.
instance.clearSession()Forget the saved cross-page session for this attempt.

Payload schema

Events are sent as JSON batches via navigator.sendBeacon() (on page exit) or fetch(..., { keepalive: true }):

Batch payload (JSON)
{
  "schemaVersion": 1,
  "clientVersion": "1.1.0",
  "kind": "batch",
  "sessionId": "tp_18f3a...",
  "examId": "FINAL_2026_06",
  "attemptId": "ATTEMPT_12345",
  "candidateLabel": "student_42",
  "sentAt": "2026-06-12T10:30:00.000Z",
  "userAgent": "Mozilla/5.0 ...",
  "language": "en-US",
  "screen": { "w": 1920, "h": 1080 },
  "timezoneOffsetMin": -360,
  "events": [
    {
      "schemaVersion": 1,
      "clientVersion": "1.1.0",
      "seq": 42,
      "clientTime": "2026-06-12T10:29:58.512Z",
      "eventType": "visibility",
      "violationKey": "tab_hidden",
      "eventData": { "visibilityState": "hidden" },
      "pageUrl": "https://exams.school.edu/final",
      "visibilityState": "hidden",
      "hasFocus": false,
      "isFullscreen": false,
      "violationCount": 3,
      "integrityScore": 75
    }
  ]
}

eventType is one of session, heartbeat, visibility, focus, fullscreen, devtools, clipboard, contextmenu, print, idle, screen, automation, input, custom. Informational events (e.g. focus regained) have violationKey: null.

Delivery is at-least-once: failed batches are re-queued with exponential backoff, and unsent events survive page changes. seq increases by one per event within a session, so (sessionId, seq) is an exact deduplication key, and a gap in seq means events never arrived. Batches stay under 48 KiB.

Useful eventData: session events carry { resumed, persisted, gapMs }; return-to-tab and focus-back events carry awayMs; insert_burst carries { inputType, chars, targetTag }.

Building a collector

The collector is the only server-side piece: an endpoint that accepts JSON batches and stores them. Any stack works.

TP/ARCH·02 SELF-HOSTED EXAM PAGE SCRIPT TAG POST /collect JSON BATCH COLLECTOR ~30 LINES · PHP / NODE INSERT STORE + REVIEW SQLITE · NDJSON · YOUR DB

PHP + SQLite (single file)

collect.php
<?php // collect.php
header('Access-Control-Allow-Origin: https://exams.school.edu');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true'); // beacons carry cookies
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }

$raw = file_get_contents('php://input');
// support data-format="form" too:
if (isset($_POST['payload'])) $raw = $_POST['payload'];
$batch = json_decode($raw, true);
if (!$batch || ($batch['kind'] ?? '') !== 'batch') { http_response_code(400); exit; }

$db = new PDO('sqlite:' . __DIR__ . '/events.sqlite');
$db->exec('CREATE TABLE IF NOT EXISTS events (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  session_id TEXT, seq INTEGER, exam_id TEXT, attempt_id TEXT, candidate TEXT,
  client_time TEXT, event_type TEXT, violation_key TEXT,
  integrity_score REAL, violation_count INTEGER, data TEXT,
  received_at TEXT DEFAULT CURRENT_TIMESTAMP,
  UNIQUE (session_id, seq)
)');
// INSERT OR IGNORE: retried batches are deduplicated by (session_id, seq)
$stmt = $db->prepare('INSERT OR IGNORE INTO events
  (session_id, seq, exam_id, attempt_id, candidate, client_time, event_type,
   violation_key, integrity_score, violation_count, data)
  VALUES (?,?,?,?,?,?,?,?,?,?,?)');
foreach (($batch['events'] ?? []) as $e) {
  $stmt->execute([
    $batch['sessionId'] ?? '', $e['seq'] ?? null, $batch['examId'] ?? '', $batch['attemptId'] ?? '',
    $batch['candidateLabel'] ?? '', $e['clientTime'] ?? '', $e['eventType'] ?? '',
    $e['violationKey'] ?? null, $e['integrityScore'] ?? null,
    $e['violationCount'] ?? 0, json_encode($e['eventData'] ?? null)
  ]);
}
http_response_code(204);

Node.js (no dependencies)

collect.mjs
// collect.mjs — node collect.mjs
import { createServer } from 'node:http'
import { appendFileSync } from 'node:fs'

const ORIGIN = 'https://exams.school.edu'

createServer((req, res) => {
  res.setHeader('Access-Control-Allow-Origin', ORIGIN)
  res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
  res.setHeader('Access-Control-Allow-Credentials', 'true') // beacons carry cookies
  if (req.method === 'OPTIONS') { res.writeHead(204).end(); return }
  if (req.method !== 'POST' || req.url !== '/collect') { res.writeHead(404).end(); return }

  let body = ''
  req.on('data', (c) => { body += c; if (body.length > 1e6) req.destroy() })
  req.on('end', () => {
    try {
      const batch = JSON.parse(body)
      if (batch.kind !== 'batch') throw new Error('bad payload')
      appendFileSync('events.ndjson', JSON.stringify(batch) + '\n')
      res.writeHead(204).end()
    } catch {
      res.writeHead(400).end()
    }
  })
}).listen(8787)
Production checklist: validate attemptId against an active attempt in your database, rate-limit per session, cap request body size, and store the raw batch for audit. Reject events for attempts that are already submitted or expired.

CORS

If the exam page and collector are on different origins, the collector must answer the OPTIONS preflight and send CORS headers (see the examples above). Notes:

  • The default JSON body (application/json) is not a CORS-safelisted type, so cross-origin requests, beacons included, need a successful preflight.
  • navigator.sendBeacon() always sends cookies. Reply with the exact page origin in Access-Control-Allow-Origin (never *) and Access-Control-Allow-Credentials: true, or the browser drops the response.
  • To skip preflight entirely, set data-format="text": the same JSON is sent as text/plain, which is safelisted. Parse the body as JSON whatever its content type.
  • For cookie-based auth on the fetch path too, set data-credentials="include".
  • Same-origin deployments (recommended) need no CORS configuration at all.

LMS & platform integration

Moodle

Add the script tag to your quiz page via a theme layout override, the "Additional HTML" admin setting (footer), or a local plugin that injects it only on mod/quiz attempt pages. Pass Moodle's attempt ID into data-attempt-id.

WordPress (LearnDash, Tutor LMS, Quiz Maker)

Enqueue the script conditionally on quiz pages with wp_enqueue_script, then print the data attributes with a script_loader_tag filter — or simply paste the tag into your quiz template.

Custom platforms

Render the script tag server-side with the attempt's real IDs. Generate data-attempt-id when the attempt starts and verify it server-side when events arrive.

Privacy & honest limits

What it never collects: no camera, no microphone, no screen recording, no keystroke contents, no clipboard contents. Events describe that something happened (e.g. "paste occurred in a textarea"), never what was pasted.

Self-hosted by design: the script and the data both live on your infrastructure. No third-party processors, which dramatically simplifies GDPR/FERPA conversations.

Honest limits: client-side JavaScript cannot see other devices or a phone next to the keyboard, and sees a second monitor only in Chromium browsers (multi_screen), and a technically skilled candidate can disable any in-page script. tinyproctor.js is a deterrence and triage layer for low/medium-stakes assessments — for high-stakes certification, combine it with stronger controls. See the honest comparison.

FAQ

Does it work on mobile?

Yes — visibility, focus, clipboard, idle, and heartbeat signals all work on mobile browsers. Fullscreen and DevTools signals are desktop-oriented.

Will it slow the exam page down?

No. It's under 7 KB gzipped, dependency-free, uses passive event listeners and batched network calls (one small POST every ~0.9s at most).

What happens if the network drops?

Events queue locally (up to queueMax) and retry with exponential backoff. On page close, the queue is flushed via sendBeacon, which browsers deliver even during unload. With an attempt ID set, unsent events are also saved in sessionStorage and sent from the next page, and Chrome/Edge additionally schedule them with fetchLater() in case the tab is killed.

Does it work with multi-page quizzes?

Yes. Use the same data-attempt-id on every page and v1.1 keeps one session, one score and one seq sequence per attempt. Page changes are not counted as tab switches. Call TinyProctor.destroy(true) after submit.

Does it detect AI agents and AI browsers?

Partly, and honestly so. Agent browsers type answers in large inserts (insert_burst), WebDriver automation sets navigator.webdriver (automation_flag), and docked AI sidebars widen the outer/inner window gap (devtools_resize). A careful agent can avoid all three, and an AI on a second device is invisible to any browser script. Treat these as triage signals for human review.

Can candidates fake a perfect score?

A sufficiently technical candidate can — this is true of every client-side tool. Use heartbeat gaps and missing-session detection server-side to flag tampering: a session with no events at all is itself a red flag.

Is it really free?

Yes — MIT licensed, free for commercial use. If it saves you a vendor contract, consider buying me a coffee to support maintenance.