Detected country: US
logo
Open AppStatusSubmit Ticket
GuideAPI References
‌
‌
‌
logo

Powered by

  • Home
  • Distribution
  • Widgets & embedding
  • Brainfish Widget - Contextual Help

Brainfish Widget - Contextual Help

14min read

Share

Overview

The Brainfish.Widgets.onContextHelp() method allows you to programmatically open the Brainfish widget with a pre-filled question. This enables you to provide contextual, in-app help based on user actions, page location, or UI interactions.

Basic Usage

Syntax

Brainfish.Widgets.onContextHelp(question: string)

Parameters

ParameterTypeRequiredDescription
questionstringYesThe question to pre-fill in the widget search

Simple Example

// Initialize the widget first

Brainfish.Widgets.init({
  widgetKey: 'your_widget_key'
});

// Later, trigger contextual help

Brainfish.Widgets.onContextHelp('How do I reset my password?');

When to Use Contextual Help

Contextual help is ideal for:

✅ Error States - Help users recover from errors

✅ Complex Forms - Provide guidance on specific form fields

✅ Feature Discovery - Explain new or complex features

✅ Onboarding - Guide new users through your app

✅ Page-Specific Help - Offer relevant help based on current page

✅ Empty States - Help users understand what to do next

❌ Don't use for:

  • General navigation (use menu links instead)
  • Marketing content (use modals/banners)
  • Critical system messages (use proper alerts)

Implementation Examples

Example 1: Help Button on Forms

Add contextual help buttons next to complex form fields:

<form>
  <div class="form-field">
    <label for="api-key">API Key</label>
    <input type="text" id="api-key" />
    <button 
      type="button" 
      onclick="Brainfish.Widgets.onContextHelp('How do I find my API key?')"
      class="help-btn"
    >
      ?
    </button>
  </div>
  
  <div class="form-field">
    <label for="webhook-url">Webhook URL</label>
    <input type="url" id="webhook-url" />
    <button 
      type="button"
      onclick="Brainfish.Widgets.onContextHelp('How do I set up webhooks?')"
      class="help-btn"
    >
      ?
    </button>
  </div>
</form>

Example 2: Error State Help

Provide help when users encounter errors:


function handleUploadError(error) {
  // Show error message
  showErrorMessage(error.message);
  
  // Offer contextual help based on error type
  if (error.code === 'FILE_TOO_LARGE') {
    document.getElementById('help-link').onclick = () => {
      Brainfish.Widgets.onContextHelp('What is the maximum file size for uploads?');
    };
  } else if (error.code === 'INVALID_FORMAT') {
    document.getElementById('help-link').onclick = () => {
      Brainfish.Widgets.onContextHelp('What file formats are supported?');
    };
  }
}

Example 3: Empty State Help

Guide users in empty states:


function renderEmptyInbox() {
  return `
    <div class="empty-state">
      <h2>Your inbox is empty</h2>
      <p>You don't have any messages yet.</p>
      <button onclick="Brainfish.Widgets.onContextHelp('How do I send my first message?')">
        Learn how to get started
      </button>
    </div>
  `;
}

Example 4: Page-Specific Help

Open contextual help based on the current page:

// Add a help button to your page

document.getElementById('page-help-btn').addEventListener('click', () => {
  const currentPage = window.location.pathname;
  
  const pageQuestions = {
    '/dashboard': 'How do I use the dashboard?',
    '/billing': 'How do I update my billing information?',
    '/settings/team': 'How do I invite team members?',
    '/integrations': 'What integrations are available?',
    '/reports': 'How do I generate reports?'
  };
  
  const question = pageQuestions[currentPage] || 'How can I help you?';
  Brainfish.Widgets.onContextHelp(question);
});

Example 5: Feature Tour

Guide users through new features:


class FeatureTour {
  constructor() {
    this.steps = [
      {
        element: '#new-feature-1',
        question: 'How do I use the new analytics dashboard?'
      },
      {
        element: '#new-feature-2',
        question: 'How do I create custom reports?'
      },
      {
        element: '#new-feature-3',
        question: 'How do I export my data?'
      }
    ];
  }
  
  showHelp(stepIndex) {
    const step = this.steps[stepIndex];
    if (step) {
      // Highlight the element
      document.querySelector(step.element).classList.add('highlight');
      
      // Open contextual help
      Brainfish.Widgets.onContextHelp(step.question);
    }
  }
}

// Usage

const tour = new FeatureTour();
tour.showHelp(0); // Show help for first step

Example 6: React Integration

Using contextual help in a React application:


import { useCallback } from 'react';

function PaymentForm() {
  const handleHelp = useCallback((question) => {
    if (window.Brainfish && window.Brainfish.Widgets) {
      window.Brainfish.Widgets.onContextHelp(question);
    }
  }, []);
  
  return (
    <form>
      <div className="form-group">
        <label>Credit Card Number</label>
        <input type="text" name="cardNumber" />
        <button 
          type="button"
          onClick={() => handleHelp('Is my payment information secure?')}
          className="help-icon"
        >
          ?
        </button>
      </div>
      
      <div className="form-group">
        <label>Billing Address</label>
        <input type="text" name="address" />
        <button 
          type="button"
          onClick={() => handleHelp('Why do you need my billing address?')}
          className="help-icon"
        >
          ?
        </button>
      </div>
    </form>
  );
}

Example 7: Vue Integration

Using contextual help in a Vue application:

<template>
  <div class="settings-page">
    <h1>Account Settings</h1>
    
    <div class="setting-item">
      <label>Two-Factor Authentication</label>
      <button @click="handleHelp('How do I set up two-factor authentication?')">
        Need help?
      </button>
    </div>
    
    <div class="setting-item">
      <label>API Access</label>
      <button @click="handleHelp('How do I generate API keys?')">
        Need help?
      </button>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    handleHelp(question) {
      if (window.Brainfish && window.Brainfish.Widgets) {
        window.Brainfish.Widgets.onContextHelp(question);
      }
    }
  }
}
</script>

Example 8: Dynamic Help Based on User Role

Provide role-specific help:


function showRoleBasedHelp(feature) {
  const userRole = getCurrentUserRole(); // Your function to get user role
  
  const helpQuestions = {
    admin: {
      users: 'How do I manage user permissions?',
      billing: 'How do I view billing history for all teams?',
      settings: 'How do I configure organization settings?'
    },
    member: {
      users: 'How do I update my profile?',
      billing: 'How do I view my subscription?',
      settings: 'How do I change my notification preferences?'
    }
  };
  
  const question = helpQuestions[userRole]?.[feature] || 'How can I help you?';
  Brainfish.Widgets.onContextHelp(question);
}

// Usage

document.getElementById('user-settings-help').addEventListener('click', () => {
  showRoleBasedHelp('settings');
});

Best Practices

1. Use Clear, Natural Questions

✅ Good:


Brainfish.Widgets.onContextHelp('How do I reset my password?');
Brainfish.Widgets.onContextHelp('What payment methods do you accept?');
Brainfish.Widgets.onContextHelp('How do I invite team members?');

❌ Bad:


Brainfish.Widgets.onContextHelp('password reset');
Brainfish.Widgets.onContextHelp('payment');
Brainfish.Widgets.onContextHelp('team');

2. Make Help Discoverable

Add visual indicators for contextual help:

<style>
  .help-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #3b82f6;
    color: white;
    font-size: 12px;
    border: none;
    cursor: pointer;
    margin-left: 8px;
  }
  
  .help-icon:hover {
    background: #2563eb;
  }
</style>

<label>
  Complex Setting
  <button 
    class="help-icon"
    onclick="Brainfish.Widgets.onContextHelp('What does this setting do?')"
  >
    ?
  </button>
</label>

3. Ensure Widget is Initialized

Always check if the widget is ready before calling onContextHelp:


function triggerContextHelp(question) {
  // Wait for widget to be ready
  if (window.Brainfish && window.Brainfish.Widgets) {
    window.Brainfish.Widgets.onContextHelp(question);
  } else {
    // Fallback: wait for widget to load
    window.addEventListener('onBrainfishReady', () => {
      window.Brainfish.Widgets.onContextHelp(question);
    }, { once: true });
  }
}

4. Track Contextual Help Usage

Monitor which contextual help triggers are most used:


function trackContextualHelp(question, context) {
  // Track with your analytics
  if (window.analytics) {
    window.analytics.track('Contextual Help Triggered', {
      question: question,
      context: context,
      page: window.location.pathname
    });
  }
  
  // Open the help widget
  Brainfish.Widgets.onContextHelp(question);
}

// Usage

trackContextualHelp('How do I reset my password?', 'login-form-error');

5. Provide Fallbacks

Handle cases where the help widget might not be available:


function showHelp(question, fallbackUrl) {
  if (window.Brainfish && window.Brainfish.Widgets) {
    Brainfish.Widgets.onContextHelp(question);
  } else if (fallbackUrl) {
    // Fallback to help center
    window.open(fallbackUrl, '_blank');
  } else {
    console.warn('Help widget not available');
  }
}

// Usage

showHelp(
  'How do I reset my password?',
  'https://help.yourcompany.com/articles/reset-password'
);

Advanced Patterns

Pattern 1: Contextual Help Manager

Create a centralized manager for all contextual help:


class ContextualHelpManager {
  constructor() {
    this.questions = new Map();
    this.isReady = false;
    
    // Wait for widget to be ready
    if (window.Brainfish && window.Brainfish.Widgets) {
      this.isReady = true;
    } else {
      window.addEventListener('onBrainfishReady', () => {
        this.isReady = true;
      });
    }
  }
  
  // Register a help trigger
  register(id, question, options = {}) {
    this.questions.set(id, {
      question,
      context: options.context || '',
      analytics: options.analytics !== false
    });
  }
  
  // Trigger help by id
  trigger(id) {
    const help = this.questions.get(id);
    if (!help) {
      console.warn(`Help trigger "${id}" not found`);
      return;
    }
    
    // Track if analytics enabled
    if (help.analytics && window.analytics) {
      window.analytics.track('Contextual Help', {
        helpId: id,
        question: help.question,
        context: help.context
      });
    }
    
    // Show help
    if (this.isReady) {
      window.Brainfish.Widgets.onContextHelp(help.question);
    } else {
      console.warn('Help widget not ready yet');
    }
  }
  
  // Batch register multiple help triggers
  registerBatch(triggers) {
    Object.entries(triggers).forEach(([id, config]) => {
      this.register(id, config.question, config);
    });
  }
}

// Initialize

const helpManager = new ContextualHelpManager();

// Register help triggers

helpManager.registerBatch({
  'password-reset': {
    question: 'How do I reset my password?',
    context: 'login-page'
  },
  'api-keys': {
    question: 'How do I generate API keys?',
    context: 'settings-page'
  },
  'billing': {
    question: 'How do I update billing information?',
    context: 'billing-page'
  }
});

// Usage throughout your app

document.getElementById('help-btn').addEventListener('click', () => {
  helpManager.trigger('password-reset');
});

Pattern 2: Smart Help Suggestions

Suggest help based on user behavior:


class SmartHelpAssistant {
  constructor() {
    this.userActions = [];
    this.helpTriggers = {
      'failed-login-3': 'How do I reset my password?',
      'empty-dashboard-30s': 'How do I get started with the dashboard?',
      'form-abandoned': 'Do you need help completing this form?',
      'feature-revisit-3': 'Would you like a tutorial on this feature?'
    };
  }
  
  trackAction(action) {
    this.userActions.push({
      action,
      timestamp: Date.now()
    });
    
    this.checkForHelpTriggers();
  }
  
  checkForHelpTriggers() {
    // Example: Detect repeated failed login attempts
    const recentLoginFails = this.userActions.filter(
      a => a.action === 'login-failed' && 
      Date.now() - a.timestamp < 60000
    );
    
    if (recentLoginFails.length >= 3) {
      this.offerHelp('failed-login-3');
    }
  }
  
  offerHelp(triggerId) {
    const question = this.helpTriggers[triggerId];
    if (!question) return;
    
    // Show a non-intrusive prompt
    const prompt = confirm(`It looks like you might need help. Would you like assistance with: "${question}"?`);
    
    if (prompt) {
      Brainfish.Widgets.onContextHelp(question);
    }
  }
}

// Usage

const assistant = new SmartHelpAssistant();
assistant.trackAction('login-failed');

Pattern 3: Multi-Step Help Flow

Guide users through complex processes:


class HelpFlow {
  constructor(steps) {
    this.steps = steps;
    this.currentStep = 0;
  }
  
  start() {
    this.showStep(0);
  }
  
  showStep(index) {
    if (index >= this.steps.length) {
      this.complete();
      return;
    }
    
    const step = this.steps[index];
    this.currentStep = index;
    
    // Show help for current step
    Brainfish.Widgets.onContextHelp(step.question);
    
    // Optionally highlight elements
    if (step.highlight) {
      document.querySelector(step.highlight)?.scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
    }
  }
  
  next() {
    this.showStep(this.currentStep + 1);
  }
  
  previous() {
    this.showStep(this.currentStep - 1);
  }
  
  complete() {
    console.log('Help flow completed');
  }
}

// Usage

const onboardingFlow = new HelpFlow([
  {
    question: 'How do I create my first project?',
    highlight: '#create-project-btn'
  },
  {
    question: 'How do I invite team members?',
    highlight: '#team-section'
  },
  {
    question: 'How do I configure notifications?',
    highlight: '#settings-link'
  }
]);

// Start the flow

document.getElementById('start-tour').addEventListener('click', () => {
  onboardingFlow.start();
});

Troubleshooting

Issue: Widget doesn't open when calling onContextHelp

Possible causes:

  • Widget not initialized yet
  • Widget script not loaded
  • JavaScript errors preventing execution

Solution:


function safeContextHelp(question) {
  try {
    if (!window.Brainfish || !window.Brainfish.Widgets) {
      console.error('Brainfish widget not loaded');
      return;
    }
    
    window.Brainfish.Widgets.onContextHelp(question);
  } catch (error) {
    console.error('Error triggering contextual help:', error);
  }
}

Issue: Question not appearing in the search

Possible causes:

  • Empty or undefined question string
  • Special characters not properly encoded

Solution:


function sanitizeQuestion(question) {
  // Ensure question is a string
  if (typeof question !== 'string') {
    console.warn('Question must be a string');
    return '';
  }
  
  // Trim whitespace
  return question.trim();
}

// Usage

const question = sanitizeQuestion(userInput);
if (question) {
  Brainfish.Widgets.onContextHelp(question);
}

Issue: Widget opens but doesn't show the question

Possible causes:

  • Race condition with widget initialization
  • Question string is too long

Solution:


function delayedContextHelp(question) {
  // Small delay to ensure widget is fully ready
  setTimeout(() => {
    Brainfish.Widgets.onContextHelp(question);
  }, 100);
}

API Reference

Method: onContextHelp(question)

Opens the Brainfish widget with a pre-filled question.

Parameters:

  • question (string, required): The question to display in the widget

Returns:

  • void

Throws:

  • May throw if widget is not initialized

Example:


Brainfish.Widgets.onContextHelp('How do I reset my password?');

Share