Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Optivise Browser SDK

A dual-mode browser SDK for visual DOM element selection and live A/B testing experiments.

Overview

Optivise SDK operates in two modes:

Editor Mode - Visual element selection for dashboard integration. Hover and click elements to capture CSS selectors, HTML, and positioning data via postMessage - perfect for building experiment creation workflows.

Visitor Mode - Live A/B testing with Statsig integration. Automatically fetches and applies DOM patches based on experiment variant assignments from Statsig.

Features

Editor Mode

  • 🎯 Visual DOM Selection - Hover and click to select elements
  • 📍 CSS Selector Generation - Automatic selector generation
  • 📊 Element Data Export - HTML, selectors, and bounding boxes via postMessage
  • 🖥️ Dashboard Integration - Seamless communication with parent dashboard

Visitor Mode

  • 🧪 Statsig Integration - Native support for Statsig experiments
  • 🔄 Automatic Patching - Fetches and applies DOM changes based on variants
  • 👤 User Targeting - Supports both identified and anonymous users
  • 🎨 Dynamic Content - Changes content without code deployments

General

  • 🚀 Easy Integration - One script tag, dual functionality
  • 📦 Bundle Size - ~23KB gzipped (includes Statsig SDK)

Quick Start

Mode 1: Editor Mode (Dashboard Integration)

For visual element selection in your dashboard:

<script 
  src="https://optivisesdk.pages.dev/optivise.js" 
  data-project="YOUR_PROJECT_ID" 
  async>
</script>

Load your website in an iframe with ?optivise_edit=true:

https://yoursite.com/?optivise_edit=true

The SDK will send element data via postMessage when users hover/click elements.

Mode 2: Visitor Mode (Live A/B Testing)

For running live experiments with Statsig:

<script>
  window.OptiviseConfig = {
    projectId: 'your-project-id', // Optional, not used for patch fetching
    statsigClientKey: 'client-YOUR_STATSIG_KEY', // Required
    experimentKey: 'optv_homepage_test_1234567890', // Required - must match statsigExperimentKey from Optivise
    userID: 'user-123', // Optional
    debug: false // optional
  };
</script>
<script 
  src="https://optivisesdk.pages.dev/optivise.js" 
  async>
</script>

The SDK will:

  1. Initialize Statsig with your client key
  2. Retrieve the variant assignment
  3. Fetch the corresponding DOM patch from your API
  4. Apply the patch automatically

Usage

Integration Example

<!DOCTYPE html>
<html>
<head>
  <title>Your Website</title>
</head>
<body>
  <div id="hero">
    <h1>Welcome to Our Site</h1>
    <button class="cta">Get Started</button>
  </div>

  <!-- Add Optivise SDK -->
  <script 
    src="https://optivisesdk.pages.dev/optivise.js" 
    data-project="my-project">
  </script>
</body>
</html>

Listening for Selected Elements

window.addEventListener('message', (event) => {
  if (event.data.type === 'optivise-element-selected') {
    console.log('Selected element:', event.data);
    
    // Use the data in your dashboard
    const { selector, outerHTML, boundingBox } = event.data;
    
    // Example: Create an experiment with this element
    createExperiment({
      targetSelector: selector,
      originalHTML: outerHTML,
      position: boundingBox
    });
  }
});

postMessage Data Format

{
  "type": "optivise-element-selected",
  "selector": "#hero h1",
  "outerHTML": "<h1>Welcome to Our Site</h1>",
  "boundingBox": {
    "x": 100,
    "y": 200,
    "width": 500,
    "height": 60
  },
  "timestamp": 1699564800000
}

Visitor Mode API

When running in visitor mode, the SDK expects a patch API endpoint:

Endpoint

GET https://api.optivise.dev/api/experiments/by-statsig-key/{statsigExperimentKey}/patch?variantKey={variant}&userId={userId}

Response Format

{
  "selector": "#hero h1",
  "newHtml": "<h1 style='color: #10b981; font-size: 3rem;'>New Headline from Variant A!</h1>"
}

How It Works

  1. SDK initializes Statsig with statsigClientKey
  2. Retrieves variant from experiment using experimentKey (must match the statsigExperimentKey from Optivise)
  3. Calls patch API with statsigExperimentKey, variantKey, and userId
  4. Applies newHtml to element matching selector

Important: The experimentKey in your SDK config must match the statsigExperimentKey that was created when you created the experiment in the Optivise dashboard. This key is automatically generated and can be found in your experiment details.

Statsig Configuration

In your Statsig experiment, add a parameter named variantKey:

  • Control group: variantKey = "control"
  • Variant A group: variantKey = "variant_a"
  • Variant B group: variantKey = "variant_b"

The SDK will skip patching for "control" variants.

Configuration

Basic Configuration

<script 
  src="https://optivisesdk.pages.dev/optivise.js" 
  data-project="YOUR_PROJECT_ID">
</script>

Advanced Configuration (Visitor Mode)

<script>
  window.OptiviseConfig = {
    // Required for visitor mode
    projectId: 'my-project',
    statsigClientKey: 'client-YOUR_KEY',
    
    // Optional
    experimentKey: 'homepage_test',  // Default: 'optv_default'
    userID: 'user-123',              // Default: anonymous
    debug: true                      // Default: false
  };
</script>
<script src="https://optivisesdk.pages.dev/optivise.js"></script>

Configuration Options

Option Required Default Description
projectId No* - Your Optivise project ID (not used for patch fetching)
statsigClientKey For visitor mode - Your Statsig client SDK key
experimentKey For visitor mode 'optv_default' Statsig experiment key (must match statsigExperimentKey from Optivise dashboard)
userID No anon_{timestamp} User identifier for Statsig
debug No false Enable detailed console logging

* projectId is optional for visitor mode. The experimentKey is used to fetch patches from the API.

Editor Mode

Activation Methods

Method 1: URL Parameter (Recommended)

https://yoursite.com/?edit=true

Method 2: localStorage

localStorage.setItem('optivise_editor', 'on');
// Reload the page

Editor Controls

When editor mode is active:

  • A visual indicator appears in the top-right corner
  • Hover over any element to see a highlight
  • Click to select and emit data
  • Press ESC to deselect (future enhancement)

Development

Prerequisites

  • Node.js 16+
  • npm 7+

Build

# Install dependencies
npm install

# Build for production
npm run build

# Development mode (watch)
npm run dev

Output

  • File: dist/optivise.js
  • Format: IIFE (Immediately Invoked Function Expression)
  • Size: ~23KB gzipped (includes Statsig SDK)
  • Target: Modern browsers (ES6+)

Testing Locally

# Start a local server
python3 -m http.server 8000

# Open test page
open http://localhost:8000/test.html?edit=true

Deployment

Cloudflare Pages (Recommended)

  1. Connect your GitHub repo
  2. Set build command: npm run build
  3. Set output directory: dist
  4. Deploy

Your SDK will be live at:

https://your-project.pages.dev/optivise.js

Custom Domain

After deployment, add a custom domain in Cloudflare Pages:

cdn.optivise.dev → your-project.pages.dev

Then update your script tag:

<script src="https://cdn.optivise.dev/optivise.js"></script>

Use Cases

Dashboard Integration

Perfect for building experiment creation dashboards where users can:

  1. Navigate to their website with ?edit=true
  2. Visually select elements they want to test
  3. Your dashboard captures the element data
  4. Create experiments based on selected elements

iframe Integration

<!-- In your dashboard -->
<iframe src="https://clientsite.com/?edit=true"></iframe>

<script>
  window.addEventListener('message', (event) => {
    if (event.data.type === 'optivise-element-selected') {
      // Show experiment modal with selected element
      openExperimentModal(event.data);
    }
  });
</script>

Browser Extension

Use in a Chrome extension to capture elements across any site:

// content.js
chrome.runtime.onMessage.addListener((msg) => {
  if (msg.type === 'enable-selector') {
    // Inject Optivise SDK
    const script = document.createElement('script');
    script.src = 'https://cdn.optivise.dev/optivise.js';
    document.body.appendChild(script);
    
    // Activate editor mode
    localStorage.setItem('optivise_editor', 'on');
    location.reload();
  }
});

API Reference

Window API

window.Optivise = {
  version: '1.0.0',    // SDK version
  config: {},          // Current configuration
  init: Function       // Re-initialize SDK
}

Configuration Options

Option Type Default Description
projectId string null Project identifier (optional)
debug boolean false Enable debug logging

Browser Support

  • Chrome 90+
  • Firefox 88+
  • Safari 14+
  • Edge 90+

Requires ES6+ support (modules, async/await, arrow functions).

Performance

  • Size: ~23KB gzipped (includes Statsig SDK)
  • Load Time: < 100ms
  • Runtime Memory: < 500KB
  • Editor mode: Zero impact when not activated
  • Visitor mode: Minimal impact, async initialization

Security

  • ✅ Minimal dependencies (Statsig SDK only)
  • ✅ Editor mode: No data sent to external servers
  • ✅ Visitor mode: Patch data fetched from your API only
  • ✅ Read-only DOM access in editor mode
  • ✅ HTTPS only
  • ✅ Content Security Policy compatible

CSP Configuration

If your site uses CSP, add:

Content-Security-Policy: script-src 'self' https://optivisesdk.pages.dev;

Troubleshooting

Editor Mode Not Activating

  1. Check URL has ?edit=true
  2. Check browser console for errors
  3. Enable debug mode: window.OptiviseConfig = { debug: true }
  4. Verify script loaded: Check Network tab

No Highlight on Hover

  1. Check z-index conflicts with other elements
  2. Ensure no other scripts are interfering
  3. Try on a different page/site

postMessage Not Received

  1. Check listener is set up before page loads
  2. Verify correct event type: optivise-element-selected
  3. Check iframe same-origin policies if using iframes

Examples

See test.html for a complete working example.

FAQ

Q: Does this work with React/Vue/Angular?
A: Yes! Works with any framework. The SDK interacts with the final DOM.

Q: Can I use this in production?
A: Editor mode is for internal use only. Don't enable on production sites accessed by end users.

Q: Does it affect page performance?
A: Editor mode has zero impact when not activated. Visitor mode adds ~23KB (gzipped) and async initialization (~100ms). Minimal impact on page load.

Q: Can I customize the highlight color?
A: Currently no, but this can be added as a configuration option.

License

MIT

Support


Version: 1.0.0
Last Updated: November 2025

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages