Now4real

Now4real

This class allows you to interact with the Now4real API.

Constructor

new Now4real()

You cannot use this constructor directly. An instance of this class is already available globally under window.now4real.

Members

(readonly) config :Now4real~Config

Configuration object that contains all the configuration values.

onerror :Now4real~onerrorCallback

Callback function called when the library has failed to load.

Example
window.now4real = window.now4real || {};
now4real.onerror = function (error) {
  console.log('Now4real failed to load', error.code, error.message)
}

onload :function

The callback function called when the library is fully loaded, and it is possible to start calling API methods.

Note that the library implements a lazy loading mechanism so that it waits for the visible state of the host page (see Page Visibility API) in order to load.

Example
window.now4real = window.now4real || {};
now4real.onload = function () {
  console.log('Now4real loaded!')
}

(readonly) pageContext :string

A constant string containing the Page Context of the current page. It is automatically computed by the library and represents the pathname of the page.

The Page Context (combined with the Site Context) allows Now4real to decide whether different users are on the same page. This directly impacts page counters, pagechats, rankings, maps, etc.

The Page Context corresponds to the window.location.pathname, with the following exceptions:

  • If the pathname terminates with /index.*, /Index.*, /home.*, /Home.*, /default.* or /Default.*, the Page Context will be truncated to the last "/".
  • If the page was loaded from the "file://" protocol, the Page Context will be "/" followed by the name of the file (including any extension).
NOTE: The query string is stripped off and does not contribute to the Page Context. This means, for example, that users on https://example.com/product?id=5&u=123 and https://example.com/product?id=18&u=789 are considered on the same page, thus sharing the same counters and pagechat.

Examples:

Url Page Context
https://example.com/path/page.html /path/page.html
https://example.com/path/page.html#hash /path/page.html
https://example.com/page5?par=val /page5
https://example.com/page5/ /page5/
http://example.com/path/index.html /path/
file:///Users/integrator/Desktop/project/app.html /app.html
http://localhost/project/app.html /project/app.html


Examples of URLs that point all to the same Page Context:

Url Page Context
https://example.com/technology/ /technology/
https://example.com/technology/index.html /technology/
https://example.com/technology/index.html /technology/
https://example.com/technology/Home.aspx /technology/
https://example.com/technology/?id=3 /technology/
https://example.com/technology/index.html?id=4 /technology/

(readonly) siteContext :string

A constant string containing the Site Context of the current page. It is automatically computed by the library and represents the website to which this page pertains. Generally, it corresponds to the window.location.host of the page, but for complex sites, a Site Context may include multiple domain name aliases and subdomains. In this case, the "master" domain is returned, which is configured in the Now4real Publisher Dashboard. Notice that the protocol (http or https) is not taken into consideration for the Site Context, but the TCP port is (only it's not 80 or 443).

The Site Context allows Now4real to decide whether different users are on the same site. This directly impacts site counters, rankings, maps, etc.

As a special case, a sandbox context is available, which allows you to test your Now4real code without mounting it on an actual domain. This context, named "shared-public-sandbox.test" automatically originates in these cases:

  • If the page is loaded with the "file://" protocol (from the file system).
  • If the hostname is "localhost".
  • If the IP address is a loopback address (like 127.0.0.1).
NOTE: the sandbox context is global and is shared among all the users. For example, imagine two developers in two different countries who put the Now4real library in some HTML pages. If they load these pages from the file system or from localhost, they will see each other's presence as if they were on the same site. Any message they post to these pagechats, as well as the page paths and page filenames, will be PUBLIC. This is a handy way to test your code with some real traffic and is also a fun way to meet other developers in real time.

Examples:

Url Site Context
http://example.com/path/page.html example.com
https://example.com/path/page2?par=val example.com
https://www.example.com/path/page3#abc example.com (if example.com was configured in the Dashboard as the master for example.com and www.example.com domains)
http://localhost:8080/project/app.html shared-public-sandbox.test
http://127.0.0.1:8080/project/dev shared-public-sandbox.test
file:///Users/integrator/Desktop/project/page.html shared-public-sandbox.test

(readonly) version :string

A constant string representing the version of the library.

Example
// returns "1.0.0"
now4real.version

Methods

get(subject) → {*}

Method that returns the current value of a subscribed subject.
It can be the latest update data object for a counter subject or the latest snapshot object for the other subjects, such as a ranking or a heatmap. See: CounterUpdate, Heatmap, MessageList, Ranking, and TypingList.

The same value can be retrieved as a property access on the Now4real instance.

Parameters:
Name Type Description
subject string

The name of the subject (which must be already subscribed to).

See subscribe for all the supported subjects.

Throws:

Will throw an instance of Now4realError, specifically one of the following: InvalidArgumentsError if the argument is not a valid subject or InvalidCallError if the subject is valid but is not currently subscribed.

Examples

Example usage of get().

// returns {value: "1"}
Now4rea.get("COUNTER_PAGE_VIEWERS")

// returns [{ isCurrentPage: true, key: 'example.com/hello.html', title: "example page", url: "http://example.com/hello.html", users: "5" }]
Now4rea.get("RANKING_PAGE_VIEWERS")

Example usage as property access.

// returns {value: "1"}
now4real["COUNTER_PAGE_VIEWERS"]

login(socialProvider) → {Promise}

Method that starts the OAuth authentication flow against the social provider.
Login is required in order to be able to post messages to the chat.

A new browser tab is opened, through which the user can sign into the chosen social network (if they aren't already signed in) and is prompted to authorize Now4real to access some information on their profile.
At the end of a successful authorization flow, we store the login information in a localStorage object of our domain, in order to make it available to any other site that integrates Now4real opened in the same browser. Accordingly, all the current browser tabs (including the one that has started the flow) will be notified through a call of the "LOGIN_STATUS" subject callback.

The method returns a promise that resolves with a loginPayload or rejects with an instance of Now4realError, specifically one of the following: AbortedError, BlockedError, InvalidArgumentsError, InvalidCallError, ServiceUnavailableError, or TechnicalProblemError.

Parameters:
Name Type Description
socialProvider string

The social login provider to use for authentication: "FACEBOOK", "GOOGLE", "LINKEDIN", or "TWITTER".

Example

Example usage of login().

now4real.login('GOOGLE')
.then(response => {
  console.log('login succedeed', response.user)
})
.catch(reason => {
  console.log('login error', reason.code, reason.message)
})

logout() → {Promise}

Method that performs a logout of the currently signed in Now4real user from the current browser.

If the call is successful, all the browser tabs (including the one that has requested the logout) will be notified through a call of the "LOGIN_STATUS" subject callback.

It returns a promise that resolves with an empty object payload or rejects with an instance of Now4realError, specifically one of the following: InvalidCallError, ServiceUnavailableError, or TechnicalProblemError.

Example

Example usage of logout().

now4real.logout()
.then(_ => {
  console.log('logout succeeded')
})
.catch(reason => {
  console.log('logout error', reason.code, reason.message)
})

post(msg) → {Promise}

Method that posts the passed message to the current pagechat on behalf of the currently logged in Now4real user.

In order for the call to be successful, the client must be connected to the Now4real cloud, and a logged-in Now4real user must be present.

The maximum length of a message and the minimum interval required between two consecutive messages is obtained through the "PARAMETERS" subject.
By consulting the "POST_STATUS" subject, instead, it is possible to know when all these preconditions are met.

It returns a promise that resolves with an empty object payload or rejects with an instance of Now4realError, specifically one of the following: DisconnectedError, InvalidArgumentsError, NotAuthenticatedError, ServiceUnavailableError, TechnicalProblemError, or TooFrequentError.

Parameters:
Name Type Description
msg string

The message that will be posted to the current pagechat.

Example

Example usage of post().

now4real.post('Hello there!')
.then(_ => {
  console.log('post succedeed')
})
.catch(reason => {
  console.log('post error', reason.code, reason.message)
})

setLoggerLevel(level) → {Promise}

Method that changes the logging level of the library.

It returns a promise that resolves with an empty object payload or rejects with an instance of Now4realError, specifically InvalidArgumentsError.

Parameters:
Name Type Description
level string

The new logging level of the library.

see Now4real~Config

startTyping() → {Promise}

Method that notifies the Now4real cloud that the current Now4real user has started typing a message for the current pagechat.

It returns a promise that resolves with an empty object payload or rejects with an instance of Now4realError, specifically one of the following: InvalidCallError or TechnicalProblemError.

stopTyping() → {Promise}

Method that notifies the Now4real cloud that the current Now4real user has stopped typing a message for the current pagechat.

It returns a promise that resolves with an empty object payload or rejects with an instance of Now4realError, specifically one of the following: InvalidCallError or TechnicalProblemError.

subscribe(subject, callback) → {Promise}

Method that sets a listener for subject updates.
The passed callback function is called each time an update pertaining to the subject has been received from the Now4real cloud with the corresponding instance of Now4realSubjectUpdate.

Two subsequent subscribe calls to the same subject (without an intermediate unsubscribe call) will result in an overwrite of the callback function.

For some subjects ["COUNTER_PAGE_VIEWERS", "COUNTER_PAGE_CHATTERS", and "COUNTER_CHAT_TYPING"] it is possible to choose a custom Page Context by appending a colon followed by the Page Context just after the subject name. [Premium Plan only]

Due to performance optimizations, after some time the page is no more visibile (typically because it is gone in the background), the subscribed subjects may no longer receive updates. The normal behavior will be restored when the page becomes visible again.

It returns a promise that resolves with an empty object payload or rejects with an instance of Now4realError, specifically one of the following: InvalidArgumentsError, InvalidCallError, or TechnicalProblemError.

Parameters:
Name Type Description
subject string

The name of the subject to subscribe to. Must be one of the following:

Name Description Category
"CONNECTION_STATUS" Notifies the application when there was a change in the status of the connection between the client and the Now4real cloud.

see ConnectionStatusUpdate
Status
"LOGIN_STATUS" Notifies the application when there was a login or a logout of a Now4real user in the current browser.

see LoginStatusUpdate
"POST_STATUS" Notifies the application when there was a change in the ability to post messages to the pagechat.

see PostStatusUpdate
"PARAMETERS" Receives the chat configuration parameters.

see ParametersUpdate
Parameter
"LIST_CHAT_MESSAGES" Receives the messages posted to the current pagechat.

see MessageListUpdate
Chat
"LIST_CHAT_TYPING" Notifies the application when a Now4real user has started or stopped typing a message for the current pagechat.

see TypingListUpdate
"COUNTER_PAGE_CHATTERS" Receives updates to the counter of chatters in the current Page Context.

see CounterUpdate
Counter
"COUNTER_PAGE_VIEWERS" Receives updates to the counter of viewers in the current Page Context (page presence counter).

see CounterUpdate
"COUNTER_SITE_CHATTERS" Receives updates to the counter of chatters in the current Site Context.

see CounterUpdate
"COUNTER_SITE_VIEWERS" Receives updates to the counter of viewers in the current Site Context (site presence counter).

see CounterUpdate
"COUNTER_CHAT_MESSAGES" Receives updates to the counter of all the messages available in the current pagechat.

see CounterUpdate
"COUNTER_CHAT_TYPING" Receives updates to the counter of all the users who are typing a message for the current pagechat.

see CounterUpdate
"RANKING_PAGE_CHATTERS" Receives ranking updates of the top pages of the site by number of chatters.

see RankingUpdate
Ranking
"RANKING_PAGE_VIEWERS" Receives ranking updates of the top pages of the site by number of viewers (presence).

see RankingUpdate
"HEATMAP_PAGE_VIEWERS" Receives heatmap updates of the geographical distribution of the viewers in the current Page Context.

see HeatmapUpdate
Heatmap
"HEATMAP_SITE_VIEWERS" Receives heatmap updates of the geographical distribution of the viewers in the current Site Context.

see HeatmapUpdate
callback Now4real~subjectUpdateCallback

Callback function that is called each time an update pertaining to the subscribed subject has been received from the Now4real cloud.

Examples

Example usage of subscribe().

now4real.subscribe('COUNTER_PAGE_VIEWERS', updObj => {
  console.log('counter update received: ' + updObj.data.value)
})
.then(response => {
  console.log('subscribe succeeded')
})
.catch(reason => {
  console.log('subscribe error', reason.code, reason.message)
})

Example usage of subscribe() with a custom Page Context. [Premium Plan only]

now4real.subscribe('COUNTER_PAGE_VIEWERS:my-great-path/test.html', updObj => {
  console.log('counter update received: ' + updObj.data.value)
})
.then(response => {
  console.log('subscribe succeeded')
})
.catch(reason => {
  console.log('subscribe error', reason.code, reason.message)
})

unsubscribe(subject) → {Promise}

Method that removes a registered listener from a subject.

It returns a promise that resolves with an empty object payload or rejects with an instance of Now4realError, specifically one of the following: InvalidArgumentsError, InvalidCallError, or TechnicalProblemError.

Parameters:
Name Type Description
subject string

The name of the subject to unsubscribe from.

See subscribe for all the supported subjects.

Example

Example usage of unsubscribe().

now4real.unsubscribe('COUNTER_PAGE_VIEWERS')
.then(response => {
  console.log('unsubscribe succeeded')
})
.catch(reason => {
  console.log('unsubscribe error', reason.code, reason.message)
})

Type Definitions

Config :object

Configuration object to be provided to the API, which contains the configuration settings.

Properties:
Name Type Default Description
target string "widget"

Defines what should be loaded.

Value Description
"none" Neither the widget nor the API will be loaded. But presence will still be silently collected.
This mode is useful, for example, when you only want to collect analytics or if you want to test Now4real in stealth mode.
"api" Only the API will be loaded.
"widget" Only the widget will be loaded.
"api+widget" Both the widget and the API will be loaded.
scope string "site"

Defines whether to create a single pagechat for the whole site or a different pagechat for every page of the site.

Value Description
"site" A single pagechat is shared among all the pages of the site. Chat messages posted by the visitors of a page can be seen on any other page. Furthermore, if the Now4real widget is used, its bubble shows only the counter of the current viewers of the site. The "site" behavior is useful for websites and blogs with small numbers of concurrent viewers because it allows users to meet easily, even if they are on different pages. On the other hand, for sites with more visitors, the "page" behavior might be preferred.
"page" Every page of the site will have a dedicated pagechat. Chat messages posted by the visitors of a page can be seen only on that page and not on other pages. Furthermore, if the Now4real widget is used, its bubble shows two counters: the current number of viewers of the current page and the current number of viewers of the site.
logger string "warn"

Defines the initial logging level of the library.

Value Description
"off" The logger is disabled; nothing is written to the console.
"error" Any error that is fatal to the current operation is logged.
"warn" Anything that can potentially cause application oddities, but that the library can recover, is logged.
"info" Changes to the connection status and any called library methods are logged.
"debug" Every internal operation is logged.
context_check string | boolean false

Should be the window.location.host of the page in which Now4real will be loaded. It is used to check whether the site was cloned and to automatically block Now4real loading.
If false is supplied, the check will not be performed.

param_overriding boolean false

Enables or disables the option to override the target and logger settings via a specific query string added to the URL of the page. If overriding is enabled and a proper query string is received, the new setting is remembered by that browser for all future visits to any pages of that site, without having to use the query string anymore.
This is quite useful to change the log level on the fly or to load the widget during a stealth test. At any time, it is possible to return to the default values by passing the "default" string to the parameters of the query string.

Value Description
false No overriding is allowed.
true Overriding is allowed and is done by adding any of the following parameters to the query string:
  • n4rTarget: overrides the target property.
    Example: https://example.com/?n4rTarget=widget
  • n4rTarget: overrides the logger property.
    Example: https://example.com/?n4rLogger=debug
widget object

Defines widget configuration settings.

Properties
Name Type Default Description
align string "left"

Defines the alignment of the widget relative to the window edges.

Value Description
"left" The widget is aligned to the window left corner.
"right" The widget is aligned to the window right corner.
align_mobile string "left"

Defines the alignment of the widget relative to the window edges, when displayed in mobile mode.

Value Description
"left" The widget is aligned to the window left corner.
"right" The widget is aligned to the window right corner.
horizontal_distance string "5px"

Defines the offset of the widget from the left/right window edge (according to the align parameter), expressed as a valid CSS length. The offset is intended from the edge of the iframe containing the widget, which has about 20px of padding.

horizontal_distance_mobile string "5px"

Defines the distance of the widget from the left/right window edge (according to the align parameter), expressed as a valid CSS length when displayed in mobile mode. The offset is intended from the edge of the iframe containing the widget, which has about 20px of padding.

vertical_distance string "5px"

Defines the distance of the widget from the window bottom edge, expressed as a valid CSS length. The offset is intended from the edge of the iframe containing the widget, which has about 20px of padding.

vertical_distance_mobile string "5px"

Defines the distance of the widget from the window bottom edge, expressed as a valid CSS length when displayed in mobile mode. The offset is intended from the edge of the iframe containing the widget, which has about 20px of padding.

color_1 string "#39aae1"

Defines the primary color used for the closed widget, expressed as a valid CSS color.

color_2 string "#fff"

Defines the secondary color used for the closed widget, expressed as a valid CSS color.

logo_url string null

Defines the URL of the logo that will be visualized on the header of the opened widget.
The supplied image is resized to fit the logo container (130px by 45px).
[Premium Plan only]

container string null

Displays the Now4real widget inside an element of the page, instead of displaying it as a page overlay.
If this property contains the id of a valid page element (usually a div), the Now4real widget will be embedded, already opened, inside that element.
The widget will adapt dynamically to the size of the container, with two constraints: a min-width of 320px and a min-height of 450px.
If this display mode is used, the following widget settings will be ignored: align, align_mobile, horizontal_distance, horizontal_distance_mobile, vertical_distance, vertical_distance_mobile, color_1, color_2.

Examples

Example of how to pass parameters to Now4real:

<script type="text/javascript">
  window.now4real = window.now4real || {};
  now4real.config = {
    target: 'api+widget',
    widget: {
      align: 'right',
      align_mobile: 'left',
      color_1: '#da3f3f',
      color_2: '#ece15d'
    }
  };
  (function () { var n4r = document.createElement('script'); n4r.type = 'text/javascript'; n4r.async = true; n4r.src = 'https://cdn.now4real.com/now4real.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(n4r, s); })();
</script>

Example of how to override the target and logger parameters:

<script type="text/javascript">
  // With the now4real.config below, the widget, the API, and the log will be disabled
  // for everyone (even if presence is still silently collected). But setting
  // param_overriding to true allows you to override such behavior for a given browser.
  // To enable the widget on the fly, just call any page of the site once with this
  // query string:
  // https://example.com/?n4rTarget=widget

  // Similarly, to set the log to debug, use this query string:
  // https://example.com/?n4rLogger=debug

  // You can use both the parameters together:
  // https://example.com/?n4rTarget=widget&n4rLogger=debug

  // That browser will remember the new settings for any future visits to any pages of
  // that site. To switch back to the original settings, just call any page of the site
  // once with this query string:
  // https://example.com/?n4rTarget=default&n4rLogger=default

  window.now4real = window.now4real || {};
  now4real.config = {
    target: 'none',
    logger: 'off',
    param_overriding: true
  };
  (function () { var n4r = document.createElement('script'); n4r.type = 'text/javascript'; n4r.async = true; n4r.src = 'https://cdn.now4real.com/now4real.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(n4r, s); })();
</script>

Heatmap :Object.<string, number>

A dictionary object that represents a Heatmap. It has string keys representing the country and number values representing the intensity.

loginPayload :object

Properties:
Name Type Description
user User

The authenticated user.

persistent boolean

false if there are restricted privacy settings on the user browser, which prevent the library from saving the authentication object into the local storage. In that case, the login will not be remembered across page navigations. true otherwise.

MessageList :array

An array that represents the messages available in the current pagechat.

Properties:
Name Type Description
id string

The unique identifier of the message.

message string

The message body.

author User

The user who sent the message.

timestamp number

The number of milliseconds from the Unix Epoch to the time the message was sent.

isMine boolean

Indicates whether the message was sent by the current Now4real user.

onerrorCallback(error) → {void}

Parameters:
Name Type Description
error Now4realError

The error encountered while loading.

Ranking :array

An array that represents a ranking.

Properties:
Name Type Description
key string

The context that uniquely identifies the page.

url string

The full url of the page.

title string

The page title, if available, otherwise the Page Context.

users string

The counter value, following the same rules of the CounterUpdate value.

isCurrentPage boolean

Indicates whether the page is the same as the one in which the library is working.

subjectUpdateCallback(subjectUpdate) → {void}

Parameters:
Name Type Description
subjectUpdate Now4realSubjectUpdate

The object that contains the update data.

TypingList :Array.<User>

An array that represents the typing list.