---
title: Methods
description: >-
  The Survicate JavaScript SDK allows you to trigger and adjust the behaviour of
  websites and web-app surveys.
source_url:
  html: 'https://developers.survicate.com/javascript/methods/'
  md: 'https://developers.survicate.com/javascript/methods.md'
---
# Overview
The Survicate JavaScript SDK allows you to trigger and adjust the behaviour of websites and web-app surveys.

JavaScript methods used to trigger Survicate surveys, except `setVisitorTraits` can only be used on some of the paid plans. Check [our pricing page](https://survicate.com/pricing/#pricing-compare-plans) for more details. We refer to this feature as 'Advanced Targeting' or 'JavaScript Targeting'.

## Using NPM packages

This section applies only to users, who decided to install Survicate tracking code either via the npm web surveys package, or npm wrapper.

Before calling any of the methods or appending event listeners, you need to initialize the Survicate JavaScript SDK.

```javascript title="Web package"
import Survicate from '@survicate/survicate-web-package/survicate_widget'

// Initialize Survicate:
const key = "..." // Workspace Key from the Survicate Panel
Survicate.init({workspaceKey: key});

// Then you can use the Survicate object:
Survicate.showSurvey('surveyId', { forceDisplay: true });

// In provided examples we will refer to the Survicate object.
```

```javascript title="Web surveys wrapper"
import { initSurvicate, getSurvicateInstance, ApiEvent } from '@survicate/survicate-web-surveys-wrapper/widget_wrapper';

  const config = { workspaceKey: 'workspace key' };

  await initSurvicate(config).then(() => {
    const survicate = getSurvicateInstance();
    survicate.showSurvey('surveyId', { forceDisplay: true });
  })

//In provided examples for Web surveys wrapper we will refer to the survicate instance, as in provided example.
```

***Please note***: In Web Surveys wrapper initSurvicate is asynchronous, so the user has to await its resolution. This should be done once, when initSurvicate hass been resolved, user can refer to `getSurvicateInstance()` as in provided example. Handling asynchronous code depends on the use case.

# Methods

## Set visitor attributes

To set the [visitor attributes](#traits) asynchronously after the script is loaded, you can use the `setVisitorTraits` method.

```javascript title="Manual implementation"
_sva.setVisitorTraits({
  "email": "Respondent's email",
  "first_name": "Respondent's name",
  "last_name": "Respondent's last name",
  "my_custom_attribute": "Custom attribute value"
});
```

```javascript title="Web package"
Survicate.setVisitorTraits({
  "email": "Respondent's email",
  "first_name": "Respondent's name",
  "last_name": "Respondent's last name",
  "my_custom_attribute": "Custom attribute value"
});
```

```javascript title="Web surveys wrapper"
survicate.setVisitorTraits({
  "email": "Respondent's email",
  "first_name": "Respondent's name",
  "last_name": "Respondent's last name",
  "my_custom_attribute": "Custom attribute value"
});
```

***Please note***: The visitor attributes will be updated locally straight away, but the change will be visible in Survicate as soon as they answer any question.

---

## Set response traits

Response traits are custom attributes tied to the current browser session. They are automatically included in survey answer payloads as part of the visit object and persist throughout the browser session. Response traits are stored in sessionStorage and are automatically cleared when the browser session ends.

### Widget surveys

For Widget surveys, you can set response traits using the `setResponseTraits` method. The method accepts an array of objects, where each object contains:
- `name` (required): The name of the attribute
- `value` (required): The value of the attribute (string, number, boolean, or Date)
- `provider` (optional): The source or integration that provided the attribute (e.g. `"hubspot"`)

```javascript title="Manual implementation"
_sva.setResponseTraits([
  { name: "campaign_id", value: "summer-2024", provider: "hubspot" },
  { name: "promo_code", value: "SAVE20", provider: "salesforce" },
  { name: "my_custom_attribute", value: "Custom attribute value" }
]);
```
```javascript title="Web package"
Survicate.setResponseTraits([
  { name: "campaign_id", value: "summer-2024", provider: "hubspot" },
  { name: "promo_code", value: "SAVE20", provider: "salesforce" },
  { name: "my_custom_attribute", value: "Custom attribute value" }
]);
```
```javascript title="Web surveys wrapper"
survicate.setResponseTraits([
  { name: "campaign_id", value: "summer-2024", provider: "hubspot" },
  { name: "promo_code", value: "SAVE20", provider: "salesforce" },
  { name: "my_custom_attribute", value: "Custom attribute value" }
]);
```

You can also initialize response traits for Widget surveys by setting them before the Survicate script loads:

```javascript
window._sva = window._sva || {};
window._sva.responseTraits = [
  { name: "campaign_id", value: "summer-2024", provider: "hubspot" },
  { name: "promo_code", value: "SAVE20", provider: "salesforce" }
];
```
---

## Retarget

Survicate triggers the targeting script to determine if a survey should be displayed to a user. This happens during events like a page load, the completion of a survey, or a path change in the Single Page Application.

If you'd like to trigger an additional targeting script execution, you can use the `retarget` method.

This feature can be especially useful for Single Page Applications / Progressive Web Applications or the callbacks of asynchronous methods.

```javascript title="Manual implementation"
_sva.retarget();
```

```javascript title="Web package"
Survicate.retarget();
```

```javascript title="Web surveys wrapper"
survicate.retarget();
```

---

## Get visitor ID

As soon as your user answers any survey's question, we assign a unique ID to them. Feel free to identify your users using that ID with the getVisitorId method

```javascript title="Manual implementation"
var visitorId = _sva.getVisitorId();
```

```javascript title="Web package"
var visitorId = Survicate.getVisitorId();
```

```javascript title="Web surveys wrapper"
var visitorId = survicate.getVisitorId();
```

***Please note***: The output of this method can be `null`. As mentioned above, the value is assigned only to the visitors that have answered any question.

---

## Reset visitor

Using the `destroyVisitor` method you can remove a user's browser data. This erases data like session history and survey responses from their localStorage and sessionStorage. However, responses already saved in our database remain untouched and can still be viewed in the survey results tab.

Be cautious:
- If a user matches a survey's targeting criteria, they might encounter the same survey again.

- If you use this method while a survey is in progress, the survey will close and the user won't be able to complete it.

```javascript title="Manual implementation"
_sva.destroyVisitor(function() {
  console.log('Data deleted');
});
```

```javascript title="Web package"
Survicate.destroyVisitor(function() {
  console.log('Data deleted');
});
```

```javascript title="Web surveys wrapper"
survicate.destroyVisitor(function() {
  console.log('Data deleted');
});
```

When using the `destroyVisitor` method, you can include a callback function to execute a specific action afterward. In this example, the callback function triggers the retarget method, which will ‘check’ if there are surveys that should be shown to this 'new' user.

```javascript title="Manual implementation"
_sva.destroyVisitor(_sva.retarget());
```

```javascript title="Web package"
Survicate.destroyVisitor(Survicate.retarget());
```

```javascript title="Web surveys wrapper"
survicate.destroyVisitor(survicate.retarget());
```

---

## Show survey

For the customers that need a custom targeting system, we provide the `showSurvey` method, that makes it easy to show an arbitrary survey based on the given survey's id.
The method ignores all targeting options, except checking whether this visitor has already answered the survey.
The method returns `true` if the survey was rendered and `false` otherwise (e.g. another survey is already displayed or the visitor has answered the desired survey).

```javascript title="Manual implementation"
_sva.showSurvey('f658c90277553239'); // You can get the Survey ID from the URL when editing it in the Survicate Panel
```

```javascript title="Web package"
Survicate.showSurvey('f658c90277553239'); // You can get the Survey ID from the URL when editing it in the Survicate Panel
```

```javascript title="Web surveys wrapper"
survicate.showSurvey('f658c90277553239'); // You can get the Survey ID from the URL when editing it in the Survicate Panel
```

Optionally, to change the default behavior of the survey, you can provide the `options` object as the second parameter.

```javascript title="Manual implementation"
var options = {
  forceDisplay: true,
  displayMethod: 'delayed',
  displayOptions: {
    delay: 5 // The survey will appear with a delay of 5 seconds
  }
};
```
```javascript title="Web package"
const options = {
  forceDisplay: true,
  displayMethod: AppearMethod.delayed,
  displayOptions: {
    delay: 5 // The survey will appear with a delay of 5 seconds
  }
};
```
```javascript title="Web surveys wrapper"
const options = {
  forceDisplay: true,
  displayMethod: AppearMethod.delayed,
  displayOptions: {
    delay: 5 // The survey will appear with a delay of 5 seconds
  }
};
```

```javascript title="Manual implementation"
_sva.showSurvey('f658c90277553239', options); // You can get the Survey ID from the URL when editing it in the Survicate Panel
```

```javascript title="Web package"
Survicate.showSurvey('f658c90277553239', options); // You can get the Survey ID from the URL when editing it in the Survicate Panel
```

```javascript title="Web surveys wrapper"
survicate.showSurvey('f658c90277553239', options); // You can get the Survey ID from the URL when editing it in the Survicate Panel
```

### options

| Property       | Type    | Description                                                                                                                                            |
|----------------|---------| ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| forceDisplay   | boolean | If true, currently rendered survey will be closed in favor of the new survey. Survey will be shown regardless of whether the user has already answered this survey.                                                                      |
| displayMethod  | string  | Use this option in order to overwrite the current displaying configuration. **Possible values: ['immediately', 'delayed', 'exitIntent', 'onScroll'].** |
| displayOptions | object  | See below for available options. **Applicable and required only for the displayMethod values 'delayed' and 'onScroll'.**                               |

### displayOptions

| Property           | Type    | Description                                                                                                      |
|--------------------|---------|------------------------------------------------------------------------------------------------------------------|
| delay              | integer | Delay in seconds. **Applicable and required only for displayMethod = 'delayed'.**                               |
| scrolledPercentage | integer | Percentage of the page that was already scrolled. **Applicable and required only for displayMethod = 'onScroll'.** |

## Close survey

Use the `closeSurvey` method to programmatically close the currently displayed survey (widget or feedback button). This triggers the same close flow as when the user clicks the close button, including the `survey_closed` event and any configured integrations.

```javascript title="Manual implementation"
_sva.closeSurvey();
```

```javascript title="Web package"
Survicate.closeSurvey();
```

```javascript title="Web surveys wrapper"
survicate.closeSurvey();
```

Optionally, pass a survey ID to close only a specific survey. This is useful when multiple widgets are displayed on the same page.

```javascript title="Manual implementation"
_sva.closeSurvey('f658c90277553239');
```

```javascript title="Web package"
Survicate.closeSurvey('f658c90277553239');
```

```javascript title="Web surveys wrapper"
survicate.closeSurvey('f658c90277553239');
```

| Parameter | Type   | Description                                                                                                    |
|-----------|--------|----------------------------------------------------------------------------------------------------------------|
| surveyId  | string | Optional. If provided, only the survey with that ID is closed. If omitted, all open surveys are closed. |

---

# Disabling automatic targeting

The targeting script is automatically executed to determine if a user fits the specified criteria. We recognize that some users might prefer a different approach, such as using custom targeting with the `showSurvey` method. If you'd like to turn off this automatic feature, use the `disableTargeting` property.

```javascript title="Manual implementation"
(function(opts) {
  opts.disableTargeting = true;
})(window._sva = window._sva || {});

// Survicate Tracking Code goes here
```

```javascript title="Web surveys wrapper"
const config = { workspaceKey: 'workspace key', disableTargeting: true };

await initSurvicate(config);
```

---

## Event-based targeting

If you need to display a survey after your site's visitor performs a specific action, use our event-based targeting. You can consider any action from your users' behavior as an event. For example, you might be interested in triggering a survey for those users who've just left the cart page without finishing the purchase. Or for those users who've just downgraded their subscription, etc.

In order to show surveys based on triggered events you can use `invokeEvent` method.

If only event name was provided in panel, pass it's name as an argument to `invokeEvent` method.

```javascript title="Manual implementation"
_sva.invokeEvent("eventName")
```

```javascript title="Web package"
Survicate.invokeEvent("eventName")
```

```javascript title="Web surveys wrapper"
survicate.invokeEvent("eventName")
```

If also event properties were provided in panel, pass them as an object to `invokeEvent` method as second argument.

***Important to note:***
- Event name, properties keys and values are case sensitive. If there is any discrepancy between what's declared in the ‘Triggers’ tab of the Target section in the Survicate panel and the  code, the survey will not appear.
- Event name can have max length of 255 characters. Longer names will be truncated to 255 characters.
- Event properties values can only be strings.

```javascript title="Manual implementation"
_sva.invokeEvent("eventName", {a: "1", b: "2"})
```

```javascript title="Web package"
Survicate.invokeEvent("eventName", {a: "1", b: "2"})
```

```javascript title="Web surveys wrapper"
survicate.invokeEvent("eventName", {a: "1", b: "2"})
```

___

## Submit survey answers without displaying a survey

In advanced scenarios, you may want to programmatically submit answers to Survicate surveys without showing the survey widget to the user. This is possible using the `hiddenSurveys`, `getSurveyPointsMetadata` and `submitAnswer` method.
This feature works for Text, Single, Rating, Numerical, CSAT and NPS.

### 1. Setting your survey frequency

In order to accept multiple responses in a short time, you need to set your survey frequency to:
"If the user has responded or closed the survey - Let the user take the survey multiple times on a recurring basis - Every time a respondent matches required criteria"

### 2. Hiding surveys from the UI

To prevent specific surveys from being displayed, pass their IDs to the Survicate tracking code using the `hiddenSurveys` property. This ensures the surveys are hidden from the user interface, but remain accessible via the JavaScript SDK.

```javascript title="Manual implementation"
(function(opts) {
  opts.hiddenSurveys = ['7d9d103a77b38925'];
})(window._sva = window._sva || {});
```

```javascript title="Web package"
const config = { workspaceKey: 'workspace key', hiddenSurveys: ['7d9d103a77b38925'] };
Survicate.init(config);
```

```javascript title="Web surveys wrapper"
const config = { workspaceKey: 'workspace key', hiddenSurveys: ['7d9d103a77b38925'] };
await initSurvicate(config);
```

You can verify which surveys are hidden by checking:
```javascript
console.log(_sva.hiddenSurveys);
```

> **Note:** Hidden surveys will not appear on the page, but you can still interact with them programmatically.

### 3. Retrieving survey points metadata

Before submitting an answer, you need to know the available questions (points) and possible answers for a given survey. Use the `getSurveyPointsMetadata` method:

```javascript
const points = _sva.getSurveyPointsMetadata('7d9d103a77b38925');
```

This returns an array of objects, each describing a survey point (question) and its possible answers:

```typescript
interface SurveyPointInfo {
  pointId: number;
  answerType: 'text' | 'rating' | 'single_choice' | 'nps' | 'csat', 'numerical';
  answers?: Array<{ id: number }>;
}
```
- `pointId`: The unique ID of the question.
- `answerType`: The type of answer expected (e.g., text, rating, single choice).
- `answers`: Optional, an array of possible answer IDs (for choice-based questions).

### 4. Submitting an answer

Once you have the point and answer IDs, use the `submitAnswer` method to send a response:

```typescript
interface SubmitAnswerParams {
  surveyId: string;
  pointId: number;
  answerId?: number; // Required for choice-based questions
  answer?: string | number; // Required for Text or NPS questions
}

submitAnswer(params: SubmitAnswerParams, responseUuid?: string): void
```

**Parameters:**
- `params`: Object containing `surveyId`, `pointId`, and either `answerId` (for choice-based questions) or `answer` (for text/NPS questions)
- `responseUuid` (optional): UUID string to group multiple submissions as part of the same response. If omitted, each submission creates a new response.

### Example: Submitting a Rating answer

```javascript
_sva.submitAnswer({
  surveyId: "7d9d103a77b38925",
  pointId: 1319375,
  answerId: 2418281
});
```

### Example: Submitting a Text answer

```javascript
_sva.submitAnswer({
  surveyId: "7d9d103a77b38925",
  pointId: 1319373,
  answer: "This is my answer"
});
```

> **Tip:** For NPS questions, provide the score as the `answer` (a number between 0 and 10).

### 4.1. Connecting submissions to a single response

You can group multiple submissions together as part of the same response by using a response UUID. This is useful when you want to submit multiple answers to the same survey and would like to see them in a single record in the Analyze tab.
> **Important:** All submissions connected with the same response UUID must be from the same survey.

#### Getting a response UUID

Use the `getResponseUuid` method to either:
- retrieve a response UUID from an active survey that was already shown to the user who submitted at least one answer or,
- generate a new response UUID:

```typescript
getResponseUuid(surveyType: 'WidgetSurvey' | 'FeedbackButton', connectResponse?: boolean): string
```

**Parameters:**
- `surveyType`: The survey type (`'WidgetSurvey'` or `'FeedbackButton'`)
- `connectResponse` (optional, default is `false`):
  - `true`: Returns the existing response UUID from an active, shown survey (requires at least one question to be answered)
  - `false` or omitted: Generates and returns a new unique UUID

#### Example: Grouping multiple submissions

Generate a UUID once and reuse it for multiple submissions:

```javascript
// Generate a response UUID
const responseUuid = _sva.getResponseUuid('WidgetSurvey');

// Submit multiple answers as part of the same response
_sva.submitAnswer(
  { surveyId: '7d9d103a77b38925', pointId: 1319375, answerId: 2418281 },
  responseUuid
);

_sva.submitAnswer(
  { surveyId: '7d9d103a77b38925', pointId: 1319376, answerId: 2418282 },
  responseUuid
);

_sva.submitAnswer(
  { surveyId: '7d9d103a77b38925', pointId: 1319373, answer: 'Additional feedback' },
  responseUuid
);
```

#### Example: Connecting to an active survey response

Link programmatic submissions to a user's active survey session:

```javascript
// Listen for when a question is answered
window._sva.addEventListener('question_answered', function(surveyId, pointId) {
  if (surveyId === '7d9d103a77b38925' && pointId === 1319375) {
    // Get the response UUID from the active survey
    const responseUuid = _sva.getResponseUuid('WidgetSurvey', true);

    // Submit additional answers to the same response
    _sva.submitAnswer(
      { surveyId: '7d9d103a77b38925', pointId: 1319376, answerId: 2418282 },
      responseUuid
    );
  }
});
```

### 5. Error handling

The SDK provides informative console warnings if something goes wrong, such as:

- `Survey with ID "7d9d103a77b389ss25" not found`
- `Point with ID "1319371113" not found in survey "7d9d103a77b38925"`
- `Answer ID "2418281111" not found in point "1319375" of survey "7d9d103a77b38925"`
- `Response UUID "a584d128-f331-401b-808d-61bbf8d9ca90" is not a valid UUID`
- `GetResponseUuid: invalid-survey-type is not supported. Please use one of the following survey types: WidgetSurvey, FeedbackButton`,

Check the browser console for these messages during development and debugging.

### 6. Verifying Submissions

All answers submitted via the SDK will be visible in the Survicate Analyze tab for your workspace.

### 7. Best Practices

- Always retrieve the latest survey points metadata before submitting answers
- Validate your input (IDs, answer types) to avoid unnecessary errors.
- Use `hiddenSurveys` only for surveys you intend to control programmatically.

---

## Set survey language

Use the `setSurveyLanguage` method to dynamically change the survey display language after the SDK has been initialized. This is useful when the user changes their language preference in your application.

```javascript title="Manual implementation"
_sva.setSurveyLanguage("de"); // ISO 639-1 language code
```

```javascript title="Web package"
Survicate.setSurveyLanguage("de"); // ISO 639-1 language code
```

```javascript title="Web surveys wrapper"
survicate.setSurveyLanguage("de"); // ISO 639-1 language code
```

**Parameters:**

| Parameter    | Type   | Description                                                                                   |
|--------------|--------|-----------------------------------------------------------------------------------------------|
| languageTag  | string | A valid [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code (e.g., `en`, `de`, `fr`, `es`, `pt`). |

***Important to note:***
- The setSurveyLanguage method should be triggered after survey is displayed.
- The language change takes effect immediately for any subsequent survey displays.
- If the specified language is not available in the survey's translations, a warning will be logged to the console and the language will not be changed.
- The forced language has the highest priority and overrides URL-based and browser-based language detection.
- To set the language during initialization, use the [`forcedLanguage` configuration option](/javascript/installation#survey-language) instead.
- If your site keeps the `<html lang>` attribute up to date (typical for localized SPAs), you can enable the [`useHtmlLangAttribute` option](/javascript/installation#detect-language-from-the-html-lang-attribute) instead of calling this method on every language change — Survicate then follows the attribute automatically.

---

## Set theme mode

Use the `setThemeMode` method to control whether surveys use light or dark theme. This is useful when you want to match your website's theme.

The default theme mode is 'auto'. Meaning that the survey will use the browser's preference for the theme.

For the dark theme to be applied, the survey's theme must have dark mode variant configured in the Survicate panel.

To set the theme during initialization, use the [`themeMode` configuration option](/javascript/installation#survey-theme)

```javascript title="Manual implementation"
_sva.setThemeMode('light'); // Force surveys to use light theme
_sva.setThemeMode('dark');  // Force surveys to use dark theme
```

```javascript title="Web package"
Survicate.setThemeMode('light'); // Force surveys to use light theme
Survicate.setThemeMode('dark');  // Force surveys to use dark theme
```

```javascript title="Web surveys wrapper"
survicate.setThemeMode('light'); // Force surveys to use light theme
survicate.setThemeMode('dark');  // Force surveys to use dark theme
```

**Parameters:**

| Parameter | Type   | Description                                                                                   |
|-----------|--------|-----------------------------------------------------------------------------------------------|
| mode      | string | Theme mode: `"light"` or `"dark"` (case-insensitive). |

***Important to note:***
- The mode parameter is case-insensitive (`"light"`, `"Light"`, `"LIGHT"` all work the same way).
- When wrong type of parameter is provided, the method will log a warning to the console and the theme mode will not be changed.
- Only `"light"` and `"dark"` modes are available via this method.

---
