# Source: https://clickwrap-developer.ironcladapp.com/docs/site-object.md

# Site Object

This reference documents the properties and methods available on the Site object.

# Properties

## Site.parameters `ParameterStore`

A DataObject used by a Site to store its properties, parameters, and various data gathered about the browsing session. The values stored in `parameters` are appended to the payload of every request sent to the Action API, where they're saved as metadata on the action.

## Site.groups `GroupStore`

An object used internally by a Site to store and reference all of the Group objects loaded within that Site. The GroupStore maintains which Groups have been `loaded`, which have been `initialized`, and any configuration options passed to the `load` command.

## Site.tasks `TaskStore`

A chain of functions that every `send` and `retrieve` command is passed through in order to **validate**, **build** and **send** a request to the Action API. Each of the tasks is described in the table below.

**Note**: If a validation task fails, the command will be aborted and a `'ps:error'` DOM event will be triggered, identifying which function failed.

### Tasks

|\_|NAME|ABORTS|DESCRIPTION|
|------|------|------|------------|
|1|`optOutTask`|True|Validates that the visitor has not opted-out of tracking.|
|2|`previewTask`|True|Validates that the browser is not in a preview or preload state.|
|3|`checkProtocolTask`|True|Validates that the protocol is either HTTP or HTTPS.|
|4|`requiredParametersTask`|True|Validates that all required parameters are present. The `access_id` parameter is always required, and `signer_id` is required for all actions except `'visited'` and `'displayed'`.|
|5|`checkStorageTask`|True|Validates that a `uuid` for the signer has been stored in a first-party cookie.|
|6|`rateLimitTask`|True|Enforces a limit of 1,000 requests per session, and throttles excessive request rate.|
|7|`buildActionTask`|False|Forms a singe URL-encoded string for the request payload by combining all of the Site's parameters with any override values that were passed into the `send` command. Parameter names are substituted with their shortened code to save bytes.|
|8|`sendActionTask`|False|Sends the payload generated by the `buildActionTask` to the Action API. Browser compatibility and the length of the payload will determine the transport type of the request: `'beacon'`, `'image'` or `'xhr'`.|

# Methods

## get

Returns the value of a parameter or property stored on the Site.

```javascript
site.get(parameter);
```

### Arguments

|\_|NAME|TYPE|DESCRIPTION|
|------|------|------|------------|
|`parameter`|True|String|The name of the parameter to return.|

### Returns

|||
|------|------------|
|`String, Number, Boolean, Object, etc.`|The value of the parameter or property, or undefined if the parameter isn't set.|

### Examples

```javascript
// Returns the "name" property.
var val = site.get('name');  // 's0'
```

```javascript
// Returns the "signer_id" parameter.
var val = site.get('signer_id');  // 'john@pactsafe.com'
```

```javascript
// Returns undefined if the parameter hasn't been set.
var val = site.get('event_callback');  // undefined
```

## set

Sets the value of one or more parameters on the Site. Accepts either a single parameter name and value, or an object of multiple parameter name and value pairs to set.

**Note**: This method only applies to *parameters*. All properties must be set when the Site object is created.

```javascript
site.set(parameter, value);
```

```javascript
site.set(parameters);
```

### Arguments

|\_|NAME|REQUIRED|TYPE|DESCRIPTION|
|------|------|------|------|------------|
|Option 1|`parameter`|True|String|The name of the parameter to set.|
||`value`|True|String, Number, Object, Function, etc.|The value of the parameter to set.|
|Option 2|`parameters`|True|Object|An object containing one or more parameter name and value pairs to set.|

### Returns

No Return Value

### Examples

```javascript
// Sets the "signer_id" parameter.
site.set('signer_id', 'john@pactsafe.com');
```

```javascript
// Unsets the "signer_id" parameter.
site.set('signer_id', null);
```

```javascript
// Sets the "event_callback" parameter.
site.set('event_callback', function(err) {
  if (err) console.error(err);
});
```

```javascript
// Sets multiple parameters at once.
site.set({ localized: true, signer_id: 'john@pactsafe.com', event_callback: submitForm });
```

```javascript
// Cannot update Site properties such as "name".
site.get('name');  // 'p0'
site.set('name', 'pactsafe');
site.get('name');  // 'p0'
```

## getByKey

Returns a Group object by key.

**Note**: Because Groups are loaded asynchronously, this method should only be used when you are certain the Group has already been loaded and initialized. For example, within the handler of an `'initialized'` event, or the callback of a load command.

```javascript
site.getByKey(key);
```

### Arguments

|NAME|REQUIRED|TYPE|DESCRIPTION|
|------|------|------|------------|
|`key`|True|String|The key of the Group to return.|

### Returns

|||
|------|------------|
|`BrowsewrapGroup` or `ClickwrapGroup`|The initialized Group object.|

### Examples

```javascript
// Returns a Group with the key "login-contracts".
var group = site.getByKey('login-contracts');
```

```javascript
// Loads a Group with the key "login-contracts".
site.load('login-contracts');
```

```javascript
// Waits to assign the Group to a local variable until it's actually
// needed for form validation within the "click" event handler.
$('#submit-login').on('click', function(evt) {
  var group = site.getByKey('login-contracts');
  if (group && group.block()) {
    alert(group.get('alert_message'));
    return false;
  }
});
```

```javascript
// Waits for an "initialized" event on the Document object
// before assigning the Group to a variable.
var group;
$(document).on('initialized', function(evt) {
  group = site.getByKey('login-contracts');
});
```

```javascript
// Uses the command queue to load a Group.
_ps('load', 'login-contracts');
```

### Mistakes to Avoid

```javascript
// Loads the Group and immediately assigns it to a local variable.
// The async "load" command hasn't finished, so "group" is undefined.
_ps('load', 'login-contracts');
var group = site.getByKey('login-contracts');  // undefined
```

## getAllGroups

Returns all of the Group objects that have been loaded by the Site.

```javascript
site.getAllGroups();
```

### Arguments

No Arguments

### Returns

|||
|------|------------|
|Array`<BrowsewrapGroup or ClickwrapGroup>`|An array containing all of the initialized Group objects.|

### Examples

```javascript
// Returns all Groups that have been loaded and initialized.
var groups = site.getAllGroups();
```

## send

Tracks an action by sending a request to the Action API.

**Note**: Any parameter values passed into the send method are treated as temporary overrides. They apply only to the current action and leave the Site's existing parameters unchanged.

```javascript
site.send(event_type, [param1, param2, ..., paramN]);
```

```javascript
site.send(event_type, [parameters]);
```

### Arguments

|\_|NAME|REQUIRED|TYPE|DESCRIPTION|
|-----|------|------|------|------------|
||`event_type`|True|String|The type of the action being sent. Supported values include: `'agreed'`, `'disagreed'`, `'displayed'`, `'visited'` and `'updated'`.|
|Option 1|`param1`, `param2`, ..., `paramN`|Conditional|Any|Parameter values that can be supplied as in-line arguments for convenience. The parameter that corresponds to each argument position varies based on the `event_type` of the send.|
|Option 2|`parameters`|Conditional|Object|A single object containing parameter name and value pairs to use for this send only.|

### Returns

No Return Value

### Examples

```javascript
// Sends an "agreed" action with in-line parameters
// for "contracts", "versions" and "group".
site.send('agreed', [ 10, 14 ], [ '5589bf606e7b9c1b1deef447', '5589bf606e7b9c1b1deef450' ], 33);
```

```javascript
// Sends an "agreed" action with a parameters object.
site.send('agreed', {
  contracts: [ 10, 14 ],
  versions: [ '5589bf606e7b9c1b1deef447', '5589bf606e7b9c1b1deef450' ],
  group: 33
});
```

```javascript
// Sends an "updated" action.
site.send('updated', {
  signer_id: 'john@pactsafe.com',
  custom_data: { first_name: 'John', gender: 'male' }
});
```

## retrieve

Retrieves the signer's latest acceptance data from the Action API.

**Note**: This method requires that the Site's `signer_id` parameter is set.

```javascript
site.retrieve(contracts, [event_callback]);
```

### Arguments

|NAME|REQUIRED|TYPE|DESCRIPTION|
|------|------|------|------------|
|`contracts`|True|Array`<Number>`|An array of contract ids to query for the signer.|
|`event_callback`|False|Function|A callback function to execute once the request is complete. The function receives four arguments: err, responseJSON, xhr and context.|

### Returns

No Return Value

### Examples

```javascript
// Sets the "signer_id" to "john@pactsafe.com".
site.set('signer_id', 'john@pactsafe.com');
```

```javascript
// Retrieves the latest version of contracts
// 10 and 14 that the signer has accepted.
site.retrieve([ 10, 14 ], function(err, data, xhr, site) {
  if (err) console.error(err);
  else console.log(data);  // { '10': '5589bf606e7b9c1b1deef447', '14': '5589bf606e7b9c1b1deef448' }
});
```

## load

Registers a Group object on the Site, and inserts a new `<script>` element on the page to load the Group's published group.js file. The group.js file contains the Group's configuration, HTML content, and `initialize` command.

**Note**: The Group object will not be available until its group.js file finishes loading and the `initialize` command has been executed. Since this occurs asynchronously, any code that needs to reference the Group should be contained in a callback function.

```javascript
site.load(key, [selector], [event_callback]);
```

```javascript
site.load(key, [options], [event_callback]);
```

```javascript
site.load(key, [event_callback]);
```

### Arguments

|\_|NAME|REQUIRED|TYPE|DESCRIPTION|
|------|------|------|------|------------|
||`key`|True|String|The key of the Group to load.|
|Option 1|`selector`|False|String|The `id` attribute of an HTML element where the Group's content will be injected.|
|Option 2|`options`False|Object|Configuration options and parameters to set on the Group object. These will override options contained in the group.js file.|
||`event_callback`|False|Function|A callback function to execute once the Group has been loaded and initialized. The function receives two arguments: err and group.|

### Returns

No Return Value

### Examples

```javascript
// Loads a Group with the key "login-contracts".
site.load('login-contracts');
```

```javascript
// Loads a Group with the key "login-contracts"
// and provides the selector "container".
site.load('login-contracts', 'container');
```

```javascript
// Loads a Group with additional configuration options
// and an event_callback function.
site.load('login-contracts', { selector: 'container', allow_disagreed: true }, function(err, group) {
  if (err) console.error(err);
  else console.log('Group ' + group.get('key') + ' initialized.');
});
```

```javascript
// Loads a Group with an event_callback function,
// but no selector or options argument.
site.load('login-contracts', function(err, group) {
  if (err) console.error(err);
  else console.log('Group ' + group.get('key') + ' initialized.');
});
```

```javascript
// Loads a Group using the command queue,
// and provides an event_callback function.
_ps('load', 'login-contracts', 'container', function(err, group) {
  if (err) console.error(err);
  else console.log('Group ' + group.get('key') + ' initialized.');
});
```

## initialize

Creates a new instance of a BrowsewrapGroup or ClickwrapGroup from a configuration object.

**Note**: This command is already included at the bottom of every group.js file, and should rarely need to be called manually.

```javascript
site.initialize(key, type, options);
```

### Arguments

|NAME|REQUIRED|TYPE|DESCRIPTION|
|------|------|------|------------|
|`key`|True|String|The key of the Group to initialize.|
|`type`|True|String|The type of Group object to initialize, `'group'` or `'badge'`.|
|`options`|True|Object|The configuration options and parameters to set on the Group object.|

### Returns

No Return Value

### Examples

```javascript
// Initializes a BrowsewrapGroup with the key "legal-badge".
site.initialize('legal-badge', 'badge', {
  key: 'ps-app-browsewrap',
  type: 'badge',
  group: 32,
  contracts: [ 10, 14 ],
  versions: [ '5589bf606e7b9c1b1deef447', '5589bf606e7b9c1b1deef450' ],
  target_selector: 'footer-legal-terms',
  style: 'floating',
  position: 'left',
  class_name: 'ps-browsewrap-badge',
  stylesheet: '<style scoped>#ps-badge-ps-app-browsewrap.ps-browsewrap-wrapper { ... }</style>',
  legal_center_url: 'https://vault.pactsafe.io/s/0207a846-d9bf-4b13-8430-1344e86ff7b1/legal.html?g=32',
  open_legal_center: true,
  always_visible: false,
  badge_text: 'Legal Terms'
});
```

## render

Invokes the `render()` method on every Group that has been loaded by the Site.

```javascript
site.render([force]);
```

### Arguments

|NAME|REQUIRED|TYPE|DESCRIPTION|
|------|------|------|------------|
|`force`|False|Boolean|If true, previously rendered Groups will be forced to re-render. By default, they will be skipped.|

### Returns

No Return Value

### Examples

```javascript
// Renders any Group that hasn't been rendered yet.
site.render();
```

```javascript
// Renders any Group that hasn't been rendered yet, and
// re-renders Groups that have already been rendered.
site.render(true);
```