Marketing Pixel
No-code AI agent detection for marketing teams using Google Tag Manager
Overview
The AgentShield Marketing Pixel is a no-code solution for detecting AI agents and bots on your website. Perfect for marketing teams, it integrates seamlessly with Google Tag Manager (GTM) and other tag management systems.
Why Use the Marketing Pixel?
For Marketing Teams
- No coding required - Install through GTM interface
- Quick deployment - Live in minutes, not days
- Easy configuration - Visual interface for settings
- A/B testing ready - Test different responses
Analytics Integration
- Google Analytics 4 - Automatic event tracking
- Custom dimensions - Rich agent detection data
- Audience building - Segment real users from bots
- Conversion tracking - Accurate conversion metrics
Bot Protection
- Ad fraud prevention - Block fake ad clicks
- Form spam protection - Stop automated submissions
- Content scraping - Protect your content
- Inventory protection - Hide pricing from competitors
Installation Methods
GTM Installation
Step 1: Import the Template
- Log into Google Tag Manager
- Navigate to Templates → Tag Templates
- Click Search Gallery
- Search for "AgentShield"
- Click Add to Workspace
- Click Add to confirm
If the template isn't in the gallery yet, you can import it manually from our GitHub repository. Download the template.tpl
file and import it using GTM's template import feature.
Manual Template Import (Alternative)
If you can't find the template in the gallery:
- Visit our GitHub repository
- Download the
template.tpl
file - In GTM, go to Templates → Tag Templates → New
- Click the ⋮ menu → Import
- Select the downloaded
template.tpl
file - Click Save
Step 2: Create the Tag
- Go to Tags → New
- Click Tag Configuration
- Select AgentShield Pixel from Custom templates
- Configure:
- API Key: Enter your AgentShield API key
- Detection Action: Choose response type
- Confidence Threshold: Set sensitivity (0.7 recommended)
Step 3: Set Triggers
- Click Triggering
- For Single Page Applications (SPAs):
- Create a History Change trigger (for React, Vue, Angular)
- Go to Triggers → New → Trigger Configuration
- Select History Change as trigger type
- Name it "All History Changes"
- Apply this trigger to your AgentShield tag
- For Traditional websites:
- Select All Pages trigger
- Optional: Add custom triggers for specific events:
- Form submissions
- Button clicks
- Scroll depth
- Time on page
SPA Tracking Note: The AgentShield pixel now automatically detects and tracks SPA navigation events including:
- History API changes (pushState/replaceState)
- Browser back/forward navigation (popstate)
- Hash changes (hashchange)
However, configuring GTM's History Change trigger ensures redundancy and allows you to track additional GTM variables with each navigation.
Step 4: Test & Publish
- Click Preview to test in debug mode
- Verify the pixel fires correctly
- Check detection events in preview
- Click Submit to publish
- Add version notes and Publish
Configuration in GTM
Basic Settings
API Key: [Your API Key]
Action on Detection: Block/Log/Redirect
Confidence Threshold: 0.7
Debug Mode: Off (On for testing)
Advanced Settings
Custom Endpoint: (leave blank for default)
Session Timeout: 1800000 (30 minutes)
Batch Events: Yes
Batch Size: 20
Send Beacon on Unload: Yes
Direct JavaScript Installation
Perfect for traditional websites, WordPress, Shopify, and any site not using a framework.
Basic Setup
Add this code to your website's <head>
or before the closing </body>
tag:
<!-- AgentShield Pixel -->
<script
src="https://kya.vouched.id/pixel.js"
data-project-id="YOUR_PROJECT_ID"
data-debug="false">
</script>
Replace YOUR_PROJECT_ID
with your actual project ID from your AgentShield dashboard.
What the pixel does automatically:
- Automatic detection - Identifies AI agents and bots on every pageview
- SPA tracking - Detects navigation in React, Vue, Angular apps
- Session persistence - Maintains session across page reloads
- User identification - Ready for
window.AgentShield.identify()
calls - Debug mode - Set
data-debug="true"
to see detailed console logs
Configuration Options
The pixel script accepts several data attributes for configuration:
<script
src="https://kya.vouched.id/pixel.js"
data-project-id="YOUR_PROJECT_ID">
</script>
Attribute | Description | Default |
---|---|---|
data-project-id | Your AgentShield project ID (required) | - |
data-debug | Enable debug console logging | false |
data-session-timeout | Session timeout in milliseconds | 1800000 (30 min) |
data-respect-dnt | Honor Do Not Track browser setting | true |
data-enable-fingerprinting | Enable browser fingerprinting | true |
Verifying Installation
After adding the pixel script, verify it's working by opening your browser's Developer Tools console:
// Check if AgentShield is loaded
console.log('Pixel loaded:', typeof window.AgentShield !== 'undefined');
// Get initialization info
console.log(window.AgentShield?.getInitInfo());
// Expected output:
// {
// version: "1.1.0",
// initialized: true,
// sessionId: "abc-123...",
// projectId: "YOUR_PROJECT_ID"
// }
If you see initialized: true
, the pixel is working correctly!
Next.js Installation
Important: Content Security Policy (CSP) Configuration
If you have Content Security Policy (CSP) headers configured, you MUST allowlist the AgentShield domain or the pixel will be blocked by your browser.
Common CSP error you'll see if not configured:
Refused to load the script 'https://kya.vouched.id/pixel.js'
because it violates the following Content Security Policy directive
Required CSP Directives:
script-src
: Must includehttps://kya.vouched.id
(to load the pixel script)connect-src
: Must includehttps://kya.vouched.id
(for API calls to send detection data)
Method 1: Update CSP Headers in next.config.js (Recommended)
Add the AgentShield domain to your existing CSP configuration:
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'Content-Security-Policy',
value: [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://kya.vouched.id",
"connect-src 'self' https://kya.vouched.id",
// ... your other CSP directives
].join('; ')
}
]
}
]
}
}
Only add https://kya.vouched.id
to your existing CSP directives. Don't replace your entire CSP policy with this example.
Method 2: Using Middleware for CSP
Create or update middleware.ts
to set CSP headers:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// Get existing CSP or create new one
const csp = response.headers.get('Content-Security-Policy') || '';
// Add AgentShield domains to script-src
const updatedCsp = csp.includes('script-src')
? csp.replace(
/script-src([^;]*)/,
'script-src$1 https://kya.vouched.id https://agentshield.io'
)
: `${csp}; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://kya.vouched.id https://agentshield.io`;
response.headers.set('Content-Security-Policy', updatedCsp);
return response;
}
Method 3: Proxy the Script (Alternative)
If you cannot modify CSP headers, proxy the script through your API:
// app/api/agentshield-pixel/route.ts
export async function GET() {
const response = await fetch('https://kya.vouched.id/pixel.js');
const script = await response.text();
return new Response(script, {
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'public, max-age=3600',
},
});
}
Then load the script from your domain:
<script src="/api/agentshield-pixel"></script>
Method 4: Self-Host the Script
Download and serve the pixel script from your public directory:
# Download the pixel script
curl https://kya.vouched.id/pixel.js > public/agentshield-pixel.js
Then reference it locally:
<script src="/agentshield-pixel.js"></script>
Self-hosting requires manual updates when new versions are released. We recommend using CSP configuration or proxying for automatic updates.
Adding the Pixel to Your App
Use Next.js's <Script>
component with strategy="afterInteractive"
for optimal performance.
The pixel script automatically detects and tracks pageviews. No additional configuration needed!
App Router (app/layout.tsx)
import Script from 'next/script';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Script
src="https://kya.vouched.id/pixel.js"
data-project-id="YOUR_PROJECT_ID"
strategy="afterInteractive"
/>
{children}
</body>
</html>
);
}
Pages Router (_app.tsx)
import Script from 'next/script';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Script
src="https://kya.vouched.id/pixel.js"
data-project-id="YOUR_PROJECT_ID"
strategy="afterInteractive"
/>
<Component {...pageProps} />
</>
);
}
Why strategy="afterInteractive"
?
- Loads after the page becomes interactive
- Doesn't block page rendering
- Optimal for analytics and tracking scripts
Security Best Practices
Trusted Domain: AgentShield uses https://kya.vouched.id
for the pixel and API endpoints.
Only add this domain to your CSP if you have CSP headers configured. Most sites don't need to configure CSP.
Testing Checklist:
- ✅ Test in development with
data-debug="true"
enabled - ✅ Check browser console for initialization message
- ✅ Verify no CSP errors in console
- ✅ Test in production with debug mode disabled
Adobe Launch Installation
Step 1: Create Data Element
- Go to Data Elements → Add Data Element
- Name: "AgentShield API Key"
- Extension: Core
- Data Element Type: Custom Code
- Code:
return 'YOUR_API_KEY';
Step 2: Create Rule
- Go to Rules → Add Rule
- Name: "AgentShield Detection"
- Events: Add "Page Bottom" or "DOM Ready"
- Actions: Add Action
- Extension: Core
- Action Type: Custom Code
Step 3: Add Pixel Code
// Load AgentShield pixel
var script = document.createElement('script');
script.src = '${process.env.NEXT_PUBLIC_CDN_URL || "https://agentshield.io"}/pixel.js';
script.onload = function() {
// Initialize with data element
window.agentshield('init', _satellite.getVar('AgentShield API Key'));
window.agentshield('track', 'pageview');
};
document.head.appendChild(script);
Step 4: Publish
- Save the rule
- Build for Development
- Test in staging
- Build for Production
Google Analytics 4 Integration
Automatic Event Tracking
The pixel automatically sends events to GA4:
// Events sent to GA4
gtag('event', 'agent_detection', {
agent_type: 'bot',
confidence: 0.85,
action_taken: 'blocked',
user_agent: 'Mozilla/5.0...',
});
Custom Dimensions Setup
- In GA4, go to Configure → Custom Definitions
- Create custom dimensions:
agent_detection_score
(Number)is_agent
(Boolean)agent_type
(Text)detection_action
(Text)
Audience Creation
- Go to Configure → Audiences
- Create "Real Users" audience:
- Condition:
is_agent = false
- Condition:
- Create "Detected Bots" audience:
- Condition:
is_agent = true
- Condition:
Conversion Tracking
// Only track conversions for real users
if (!agentshield.isAgent()) {
gtag('event', 'conversion', {
send_to: 'AW-XXXXX/XXXXX',
value: 100.0,
currency: 'USD',
});
}
Common Use Cases
E-commerce Protection
// Hide prices from scrapers
agentshield('onDetection', function (result) {
if (result.isAgent && result.confidence > 0.8) {
// Hide or modify pricing
document.querySelectorAll('.price').forEach(function (el) {
el.textContent = 'Login for pricing';
});
}
});
Form Spam Prevention
// Block form submission for detected agents
document.getElementById('form').addEventListener('submit', function (e) {
if (agentshield.isAgent()) {
e.preventDefault();
alert('Please verify you are human');
// Show CAPTCHA or challenge
}
});
Content Protection
// Protect premium content
agentshield('onDetection', function (result) {
if (result.isAgent) {
// Replace content with placeholder
document.getElementById('premium-content').innerHTML =
'<p>This content is available to registered users only.</p>';
}
});
Ad Fraud Prevention
// Don't load ads for bots
agentshield('ready', function () {
if (!agentshield.isAgent()) {
// Load ad scripts only for real users
loadAdsense();
loadDisplayAds();
}
});
Testing Your Installation
Using GTM Preview Mode
- Click Preview in GTM
- Enter your website URL
- Open the Tag Assistant
- Verify:
- AgentShield tag fires on page load
- Events are being sent
- No JavaScript errors
Browser Console Testing
// Check if pixel is loaded
console.log(typeof agentshield); // Should be 'function'
// Check detection status
agentshield('getStatus', function (status) {
console.log('Detection status:', status);
});
// Manually trigger detection
agentshield('detect', function (result) {
console.log('Detection result:', result);
});
User Agent Testing
Test with different user agents:
# Test with bot user agent
curl -H "User-Agent: Googlebot/2.1" https://yoursite.com
# Test with normal browser
curl -H "User-Agent: Mozilla/5.0..." https://yoursite.com
JavaScript API Reference
The pixel exposes a window.AgentShield
object with methods for user identification and session management.
Available Methods
// Identify a user (for user tracking)
window.AgentShield.identify(userId, traits);
// Reset user identification (on logout)
window.AgentShield.reset();
// Get current identified user
window.AgentShield.getUser();
// Get session information
window.AgentShield.getSession();
// Track custom events
window.AgentShield.track(eventName, data);
// Get initialization status (debugging)
window.AgentShield.getInitInfo();
// Grant consent for cookies (GDPR)
window.AgentShield.grantConsent();
Method Details
identify(userId, traits)
Associates a user with the current session. Call this when users log in.
window.AgentShield.identify('user_123', {
email: 'user@example.com',
name: 'John Doe',
plan: 'premium',
});
reset()
Clears user identification. Call this when users log out.
window.AgentShield.reset();
getUser()
Returns the currently identified user or null
.
const user = window.AgentShield.getUser();
// Returns: { id: 'user_123' } or null
track(eventName, data)
Track custom events.
window.AgentShield.track('button_click', {
button: 'signup',
page: '/pricing',
});
For complete user identification documentation, see the User Identification guide.
Troubleshooting
Pixel Not Loading
- Check API key is correct
- Verify script tag is in
<head>
- Check for Content Security Policy blocks
- Ensure no ad blockers are interfering
Events Not Tracking
- Enable debug mode
- Check browser console for errors
- Verify triggers in GTM
- Test in incognito mode
Detection Not Working
- Check confidence threshold
- Verify API endpoint is accessible
- Review user agent string
- Test with known bot user agents
Privacy & Compliance
Always comply with privacy regulations in your jurisdiction. The pixel respects user privacy preferences by default.
GDPR Compliance
// Wait for consent
if (hasUserConsent()) {
agentshield('init', 'API_KEY');
} else {
// Delay until consent granted
onConsentGranted(function () {
agentshield('init', 'API_KEY');
});
}
Cookie Settings
agentshield('init', 'API_KEY', {
useCookies: false, // Disable cookies
useLocalStorage: false, // Disable local storage
sessionOnly: true, // Session data only
});
Best Practices
- Start with logging before blocking
- Test thoroughly before production
- Monitor false positives in analytics
- Adjust thresholds based on your traffic
- Use custom events for important actions
- Respect user privacy and preferences
- Keep API keys secure using environment variables
Next Steps
- GTM Setup Guide - Detailed GTM configuration
- Analytics Integration - GA4 and analytics setup
- Custom Events - Track custom interactions
- Advanced Configuration - Fine-tune detection