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) ErrorCode :ErrorCode

Enum encompassing all potential error codes in Now4real.

(readonly) Subject :Subject

Enum representing subscribable subjects in Now4real.

(readonly) config :Now4real~Config

Configuration object that contains the configured values.

onerror :Now4real~onerrorCallback

Callback function called when the library has failed to load.

Example
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 = {};
now4real.onload = function () {
  console.log('Now4real loaded!')
}

(readonly) pageContext :string

A constant string containing the Page Context of the current page. It's configurable through the page_context property of the config object, otherwise it is automatically computed by the library.

The Page Context (combined with the Site Context) allows Now4real to decide whether different users should be considered present on the same page. The term "page" means an actual web page or some logical context (group of pages, virtual place, etc.). This directly impacts page counters, pagechats, rankings, maps, etc.

The default 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: By default, 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.htm /technology/
https://example.com/technology/Home.aspx /technology/
https://example.com/technology/?id=3 /technology/
https://example.com/technology/index.html?id=4 /technology/

If the page_context property of the config object is used, the behavior of the examples above might be very different. For example, you may include some query parameters, or you may completely remap the actual page path to a different name. Please refer to the documentation of the page_context property for a few examples.

(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.

If a hierarchy of domain name aliases and subdomains has been configured in the Now4real Publisher Dashboard, the value may be different from window.location.host: for the top-level site, the configured "master" domain is returned; for a subdomain, the first subdomain name in the subdomain group is returned.

Notice that the protocol ("http://" or "https://") is not considered for the Site Context. The TCP port is considered only if 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)
https://example.com:8443/path/page.html example.com:8443
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

closePoll(removeopt) → {Promise}

Method that allows closing the currently open poll in the current Page context.

Once closed, the results will be frozen, and users will no longer be able to vote, although they will still be able to view the results. Optionally, by passing the "remove" parameter as true, you can completely remove the current poll.

The method can only be called by users with the moderator or guest role and only if there is an open poll in the current Page context.

If successful, the "POLL_STATUS" and "POLL" subjects will receive an update with the "closed" field of the poll object set to true. If removed, they will receive null instead. At this point, it is possible to open a new poll again using the createPoll method.

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.

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

[Not in Free Plan]

Parameters:
Name Type Attributes Description
remove boolean <optional>

A boolean value indicating whether to completely remove the poll. Default is false.

Example

Example usage of closePoll().

// close the current poll
await now4real.closePoll()

// completely remove the current poll
await now4real.closePoll(true)

createPoll(question, answers, optionsopt) → {Promise}

Method that allows opening a poll in the current Page context.

Polls enable users to express their preference related to the posed question; they are entirely anonymous and optionally allow multiple-choice answers.

The method can only be called by users with the moderator or guest role, and only if there isn't already another poll open in the same Page context.

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.

If successful, this call will trigger an update for the "POLL_STATUS" and "POLL" subjects, providing information about the newly opened poll.

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

[Not in Free Plan]

Parameters:
Name Type Attributes Description
question string

The question of the poll. Must be maximum 100 characters.

answers Array.<string>

An array containing the possible answers for the poll. Each answer must be maximum 25 characters. Must contain between 2 and 10 answers.

options object <optional>

An optional object containing additional options.

Properties
Name Type Attributes Description
multipleChoice boolean <optional>

Specifies whether the poll allows multiple choices. Default is false.

Example

Example usage of createPoll().

await now4real.createPoll('What is your favorite music genre?', ['Rock', 'Pop', 'Metal'], { multipleChoice: false })

deleteMessage(msgId) → {Promise}

Method that deletes the message with the passed msgId from the current pagechat.

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.

Each user can only request the deletion of their own messages. Moderators can delete any messages.

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

Parameters:
Name Type Description
msgId string

The id of the message to delete.

Example

Example usage of deleteMessage().

now4real.deleteMessage('MSG_ID_000000042')
.then(_ => {
  console.log('deleteMessage succedeed')
})
.catch(reason => {
  console.log('deleteMessage error', reason.code, reason.message)
})

editUserProfile() → {Promise}

Method that opens a new browser tab in which the user has the possibility to edit some attributes of their profile, created previously with email signup.

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

After a successful update of the user profile, all the subjects that contain a reference to that user will receive an update.

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

Example

Example usage of editUserProfile().

now4real.editUserProfile()
.then(_ => {
  console.log('edit popup opened')
})
.catch(reason => {
  console.log('error on opening edit popup', reason.code, reason.message)
})

flushChat() → {Promise}

Method that entirely flush the current pagechat. It can be called only by a logged in Moderator.

If the call is successful, the "LIST_CHAT_MESSAGES" subject will receive a series of "REMOVE" updates which lead to empty the chat.

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

Example

Example usage of flushChat().

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

get(subject) → {*}

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

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

Parameters:
Name Type Description
subject Subject | string

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

See Subject 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"}
now4real.get(now4real.Subject.COUNTER_PAGE_VIEWERS)

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

Example usage as property access.

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

getMute(userId) → {Promise}

Method that gets the configured mute period for the user, if any.

It returns a promise that resolves with a mutePayload or null, depending on the presence of the mute for the user, or rejects with an instance of Now4realError, specifically one of the following: AbortedError, DisconnectedError, InvalidArgumentsError, NotAuthenticatedError, ServiceUnavailableError, or TechnicalProblemError.

Parameters:
Name Type Description
userId string

The id of the user.

Example

Example usage of getMute().

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

getPollVote() → {Promise}

Method that allows obtaining the vote of the currently authenticated user in the current poll.

The method can only be called if there is a poll, even if closed, in the current Page context.

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.

It returns a promise that resolves with a getPollVotePayload or rejects with an instance of Now4realError, specifically one of the following: AbortedError, DisconnectedError, InvalidCallError, NotAuthenticatedError, NotFoundError, ServiceUnavailableError, or TechnicalProblemError.

[Not in Free Plan]

Example

Example usage of getPollVote().

// retrieve the vote submitted by the user, indicating their choice for the first option
const { vote } = await now4real.getPollVote()

console.log(vote) // output: [0]

login(provideropt) → {Promise}

Method that initiates the authentication flow in a new browser tab.
Login is required in order to be able to post messages to the chat.

The specific flow the user will follow depends on how the current site has been configured in the Now4real Dashboard (see the "Authentication" tab in site settings). Please consider that this method doesn't work when "JWT authentication" is selected.

In case of "Social and email login" configuration, the user navigates to a page in which they chooses the authentication provider. This step is perfomed only if the provider parameter is not defined.
If a social provider is chosen, the user proceeds with authentication on the selected social network (if not already signed in) and is prompted to authorize Now4real to access some information on their profile. If the email provider is choosen, the user is taken to a profile creation page in our system (if it doesn't exist), where they can select their preferred email and a custom nickname. The flow is passwordless and involves entering a 6-digit code sent to the chosen email.

In case of "No registration" configuration, the user can simply enter a nickname to join the chat without any registration.

Upon successful authentication, the login information is stored in a localStorage object within our domain. For the "Social and email login" configuration, this information is available to other sites with the same authentication configuration that integrate Now4real and are opened in the same browser. Furthermore, all the browser tabs which have a compatible authentication (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, AlreadyStartedError, BlockedError, InvalidArgumentsError, InvalidCallError, ServiceUnavailableError, or TechnicalProblemError.

Parameters:
Name Type Attributes Description
provider string <optional>

The login provider to use for authentication. It can be "EMAIL" or one of the supported social providers: "FACEBOOK", "GOOGLE", "LINKEDIN", or "TWITTER" (for backward compatibility, we still use the string "TWITTER" even if that platform has been rebranded to X).

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: AbortedError, 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, optionsopt) → {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 allowed message length can be retrieved from the "PARAMETERS" subject, while the minimum interval between two consecutive messages is provided in the response of a successful invocation.

It returns a promise that resolves with a postPayload or rejects with an instance of Now4realError, specifically one of the following: AbortedError, ChatbotError, ChatDisabledError, DisconnectedError, InvalidArgumentsError, NotAuthenticatedError, NotAuthorizedError, ServiceUnavailableError, TechnicalProblemError, TooFrequentError, or UserMutedError.

Parameters:
Name Type Attributes Description
msg string

The message that will be posted to the current pagechat.

options Now4real~PostOptions <optional>

The options for the current operation.

Examples

Example usage of post().

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

Example usage of post() with options.

now4real.post('Thanks for the code!!!', { replyTo: 'MSG_ID_000000037' })
.then(_ => {
  console.log('post succedeed')
})
.catch(reason => {
  console.log('post error', reason.code, reason.message)
})

registerUserConsent() → {Promise}

Method that notifies the Now4real cloud that the current logged-in JWT user has accepted Now4real's Terms of Service and Privacy Policy.

This method must be called, in case of custom authentication, before a user sends their first message. Otherwise, any call to the post method would throw an error. A check of the consentGiven attribute of the current user allows you to understand if the user has already provided their consent and therefore there is no need to call this method again.

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

If successful, this call will trigger an update for the 'POLL_STATUS' and 'POLL' subjects, providing information about the newly opened poll.

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

Example

Example usage of registerUserConsent() along with the post() method.

const currentUser = now4real.LOGIN_STATUS.user

if (!currentUser.consentGiven) {

  // here the user has to explicitly accept Now4real's Terms of Service and Privacy Policy

  // the consent must be stored on the Now4real cloud
  await now4real.registerUserConsent()
}

await now4real.post('Hi!')

reload()

Method that requests Now4real reinitialization. Once the reloading process is complete, a call to the onload callback will be re-issued.

It is advisable to call the method only when there are no other calls awaiting resolution. If this happen, the calls would be aborted and their outcome would not be guaranteed.

It can be used to update the launch configuration without the need for a page refresh.

Developers that want to support their SPA sites, offering a different pagechat for each route, can call this method when navigation occurs, to update the Now4real widget context. In this case, the widget must be loaded with a page scope. Remember that, if the SPA is based on hashed URL paths, the page_context parameter needs to be configured and updated accordingly.

Examples

Example usage of reload() to update the widget configuration.

// update widget configuration
now4real.config.widget.color_external_background = '#123456'

now4real.reload()

Example usage of reload() in a SPA using Vue Router.

// detect navigation
watch:{
    $route (to, from) {
        now4real.reload()
    }
}

Example usage of reload() in a SPA based on hashed URL paths, using Vue Router.

// detect navigation
watch:{
    $route (to, from) {
        now4real.config.page_context = '/chat/' + location.hash
        now4real.reload()
    }
}

reportMessage(msgId, reason, commentopt) → {Promise}

Method that allows a user to report a message published by other users on the current pagechat, if he finds any issues with it.

Reports containing these messages will be sent to the email addresses configured in the "User Reporting" section of the Dashboard (according to the configured frequency), who can then decide whether to remove these from the pagechat.

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.

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

Parameters:
Name Type Attributes Description
msgId string

The id of the message to report.

reason string

The reason of the report. Must be one of the following:

Reason Description
"HATE_SPEECH" Hate speech or bullying.
"VIOLENCE" Terrorism or violence.
"PORNOGRAPHY" Sexually inappropriate.
"SPAM" Spam, scams, or fraud.
"SELF_INJURY" Suicide or self-injury.
"COPYRIGHT" Intellectual property infringement.
"OTHER" Other.
comment string <optional>

Additional information the user want to include in the report.

The supplied string can contain up to 500 characters.

sendVote(vote) → {Promise}

Method that allows users to submit a vote in the current poll. This can contain a single preference or more, depending on whether the poll is single-choice or multiple-choice.

The method can only be called if there is an open poll in the current Page context.

Upon calling, the "POLL" subject will receive an update containing the updated poll results.

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.

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

[Not in Free Plan]

Parameters:
Name Type Description
vote Array.<number>

An array of numbers indicating the 0-based index of the poll answers that the user wants to vote for.
For single-choice polls, the array can contain only one number, while for multiple-choice polls, the user can vote for a maximum of all the available options.

Example

Example usage of sendVote().

// the user votes for the first answer in the current single-choice poll
await now4real.sendVote([0])

// the user votes all the answers in the current multiple-choice poll
await now4real.sendVote([0, 1, 2])

setChatEnabled(enabled) → {Promise}

Method that allows to disable or re-enable the current pagechat. It can be called only by a logged in Moderator.

If the call is successful, the "PARAMETERS" subject will be notified with the updated chatStatus value.

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

Parameters:
Name Type Description
enabled boolean

false to disable to chat, true to re-enable it.

Example

Example usage of setChatEnabled().

now4real.setChatEnabled(false)
.then(_ => {
  console.log('setChatEnabled succeeded')
})
.catch(reason => {
  console.log('setChatEnabled 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 one of the following: AbortedError, or InvalidArgumentsError.

Parameters:
Name Type Description
level string

The new logging level of the library.

see Now4real~Config

setMute(userId, duration) → {Promise}

Method that allows to mute a user in the pagechat for a period of time. The user cannot post any messages until the mute expiration.

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

It can be called multiple times on the same user, even before the expiration. The mute period will be recomputed and updated at each call.

It returns a promise that resolves with a mutePayload or rejects with an instance of Now4realError, specifically one of the following: AbortedError, DisconnectedError, InvalidArgumentsError, InvalidCallError, NotAuthenticatedError, ServiceUnavailableError, or TechnicalProblemError.

Parameters:
Name Type Description
userId string

The id of the user to mute.

duration number

The period of time, in seconds, in which the user will be muted and can't post messages. It is possible to pass null to mute the user forever.

Example

Example usage of setMute().

now4real.setMute('USER_ID_0000000099', 60)
.then(response => {
  console.log('setMute succeeded, the user is muted until: ' + new Date(response.expiration).toUTCString())
})
.catch(reason => {
  console.log('setMute error', reason.code, reason.message)
})

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: AbortedError, InvalidCallError, NotAuthorizedError, 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: AbortedError, 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.

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. [Not in Free Plan]

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: AbortedError, InvalidArgumentsError, InvalidCallError, NotAuthorizedError, or TechnicalProblemError.

Parameters:
Name Type Description
subject Subject | string

The name of the subject to subscribe to. Must be one of the values defined in the Subject enum.

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().

await now4real.subscribe(now4real.Subject.COUNTER_PAGE_VIEWERS, updObj => {
  console.log('counter update received: ' + updObj.data.value)
})

Example usage of subscribe() with a custom Page Context. [Not in Free Plan]

await now4real.subscribe(`${now4real.Subject.COUNTER_PAGE_VIEWERS}:my-great-path/test.html`, updObj => {
  console.log('counter update received: ' + updObj.data.value)
})

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: AbortedError, InvalidArgumentsError, InvalidCallError, or TechnicalProblemError.

Parameters:
Name Type Description
subject Subject | string

The name of the subject to unsubscribe from.

See Subject for all the supported subjects.

Example

Example usage of unsubscribe().

await now4real.unsubscribe(now4real.Subject.COUNTER_PAGE_VIEWERS)

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
page_context string | object null

Defines a custom Page Context for the current page. This gives you full control over how Now4real should treat each page of your site, allowing you to consider even query strings and fragments, or to override the page path completely.

It accepts a string or a Page context configurator object. If null, the default Page Context is used.

Pass a string if you want to override the page path and assign your logical context. This is useful, for example, if you want to define groups of pages that should be treated as having the same context (thus counting all the users on those pages together and providing them with a shared pagechat).
The string must always start with a "/" character.

Pass a Page context configurator object if you want to customize the Page context by defining simple rules to be applied to the URL of your page. The object accepts the properties below:

Properties
Name Type Description
query boolean | Array.<string> | RegExp Boolean: Defines whether to insert all the query parameters of the current page in the context.

Array.<string>: Alternatively, you can specify a list of query attributes to keep.

RegExp: For advanced cases, define a matcher RegExp to select which query attributes should be kept or discarded.

In all the cases, the context is created by alphabetically reordering the kept attributes, removing duplicates, and cleaning up the query string.
fragment boolean Defines whether to insert the fragment (hash) of the current page in the context. This is especially useful for single-page applications (SPA).


Examples:
Current URL: https://example.com/shop/shoes?type=sneakers&sort=price_ascending#comments
page_context pageContext
page_context: null /shop/shoes
page_context: '/shoes' /shoes
page_context: { query: true, fragment: true } /shop/shoes?sort=price_ascending&type=sneakers#comments
page_context: { query: ['type'], fragment: false } /shop/shoes?type=sneakers
page_context: { query: /^(type|brand)$/, fragment: true } /shop/shoes?type=sneakers#comments
page_context: { query: /^(?!(userId|secret)$)(\w*)$/, fragment: true } /shop/shoes?sort=price_ascending&type=sneakers#comments

WARNING: Ensure you strip any sensitive attributes, like usernames, passwords, tokens, unique ids, etc. Page contexts may easily get public (for example, in page rankings).

NOTE: Please consider that the resulting pageContext is also used to create the links in the PAGES section of the widget (that is, the url property of RankingUpdate). If you are displaying the PAGES section, ensure the resulting URLs are valid because users may click those links.
Defining a custom page_context may be useful even when the scope is set to "site", in case you want to alter the URLs displayed in the PAGES section of the widget.
custom_auth object

Defines custom authentication settings. [Not in Free Plan]

Check out Custom Auth documentation for full details and examples.

Properties
Name Type Default Description
enabled boolean false

Enables or disables the custom authentication on the current session. By activating it, it is possible to authenticate the pagechat through the user currently logged into the site.

signin_url string null

A URL where the user can sign in. It is displayed at the bottom of the chat box in case the Now4real widget is used.

jwt string | function null

The JWT token that identifies the currently logged in user on the site.

You can provide it directly as a string or through a resolver function, which must return the token through a Promise. In the latter case, the resolver function is also utilized later for token refresh.

Token refresh is managed by the API, triggering the resolver function some time before the current token expires. The resolver function should furnish a new token representing the same user but with an updated expiration time. This process ensures that the user remains authenticated without having to log in again, ensuring a seamless experience.


Examples:
jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyODM3MTI3IiwibmFtZSI6IkphY2sgUGFyayIsInBpY3R1cmUiOiJodHRwczovL2V4YW1wbGUuY29tL2phY2twYXJrLnBuZyJ9.CIrlJRW-6RBVxQ3jArGqeIwkf6xMSUp_4dRGOWFfd-I'
jwt: () => backend.getCurrentUser() // returns a Promise which resolves with the jwt
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 closed 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 closed 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 closed 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 closed 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_external_background string "#39aae1"

Defines the background color used in the closed widget, expressed as a valid CSS color.

color_external_text string "#fff"

Defines the text color used in the closed widget, expressed as a valid CSS color.

color_internal_background string "#39aae1"

Defines the background color used in the open widget, expressed as a valid CSS color.

color_internal_text string "#fff"

Defines the text color used in the open 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 open widget.

If null, the default Now4real logo is used.

The supplied image is resized to fit the logo container (130px by 45px) and the URL must use the HTTPS protocol.

[Not in Free Plan]

chat_bubbles boolean true

Displays new chat messages for the current pagechat in a bubble above the closed widget.

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 open, 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_external_background, color_external_text.

chat_enabled boolean true

Defines whether to show the chat tab inside the open widget. If set to false, it also disables the appearance of the default attention grabber above the closed widget.

ranking_enabled boolean true

Defines whether to show the ranking tab inside the open widget.

map_enabled boolean true

Defines whether to show the map tab inside the open widget.

typing_enabled boolean true

Defines whether to display the typing indicator at the bottom of the chat tab in the open widget.

user_identicon boolean false

Defines whether to show an identicon image near the name of each user in the current pagechat, so that they can be uniquely identified.
Moderators always see these icons, irrespectively of the configuration.

welcome_message string null

Defines the welcome message shown in the pagechat.

If null, a default welcome message is shown, based on the language defined in the language parameter.

It's recommended to include in the welcome message a reference to the duration of the messages in the chat. Use the {{ time }} and {{ timeUnit }} placeholders, which represent respectively a number and a time-unit. They will be replaced with the configured duration and the time unit will be automatically translated to the current user language. To avoid ambiguities, use this in conjunction with the language parameter.

The supplied string can contain up to 300 characters, including emoji Unicode and the following HTML tags: <a>, <br>.

If an empty string is supplied, no welcome message will be visualized (even the default welcome message will be turned off).

[Not in Free Plan]


Example:
welcome_message: 'Chat with the other visitors in real-time. Please follow our <a href="https://example.com/rules">guidelines</a>.<br>Messages disappear after {{ time }} {{ timeUnit }}.<br>Enjoy! ⚡'

welcome_message_img_url string null

Defines the URL of the image shown near the welcome message.

If null, the default "now" icon is used.

The supplied image must have an aspect ratio of 1:1 (square image) with a minimum width of 36px and the URL must use the HTTPS protocol.

It can be configured even without configuring a custom welcome message. This way, it's possible to replace the icon of the default welcome message.

[Not in Free Plan]

language string null

Forces the use of a specific language for the widget.

If null, the browser language is automatically chosen, if supported. If the browser language is not supported, English is used.

This can be particularly useful if you want to embed the Now4real widget on a multilingual site with different pages for different languages.

The parameter accepts alpha-2 language codes, see the currently supported languages.

attention_grabber_enabled boolean true

Defines whether to show an attention grabber message in a bubble above the closed widget.

The default message shows the total number of visitors and explains the chat capabilities of the widget by inviting the users in the same context to communicate with each other. It is automatically translated to the current user language.

If a user closes the bubble with the message, the widget will no longer show it for one day in the same browser instance.

The message can be easily customized through the attention_grabber property.

attention_grabber string null

Defines a custom message to be shown inside the attention grabber bubble. Please remember that the attention grabber shows up only when there are at least 3 users in the current context.

If null, the default attention grabber is shown, based on the language defined in the language parameter.

It's possible to use the {{ currentVisitors }} and {{ currentVisitorsMinusOne }} placeholders to embed the number of users on the current pagechat; they will be replaced with the current values and will change in real time. Note that, in the case of contexts in which there are more than 999 users, the API will expose approximated counters (e.g. 1.5K, 1M, etc) and the 2 values will be the same.

The supplied string will be limited to 140 characters after replacing all the placeholder occurrences. The string can contain emoji Unicode.

To avoid ambiguities, use this in conjunction with the language parameter.

[Not in Free Plan]


Examples:
attention_grabber: 'Chat with the other visitors! ⚡'
attention_grabber: 'There are {{ currentVisitors }} visitors here!'
attention_grabber: 'There are {{ currentVisitorsMinusOne }} other people besides you'
consent_message string null

Consent message for the acceptance of custom terms of service and privacy policy.

The supplied string can contain up to 300 characters and include <a> HTML tags.

In case of "JWT authentication" without White Label, the message is shown right after the standard Now4real consent message when a user tries to post their first message in a pagechat of the current site.

In case of "JWT authentication" with White Label, the message is shown in place of the standard Now4real consent message when a user tries to post their first message in a pagechat of the current site.

In case of "Email login" or "No registration" without White Label, the message is shown upon user’s sign up right after the standard Now4real consent message.

In case of "Email login" or "No registration" with White Label, the message is shown upon user’s sign up in place of the standard Now4real consent message.

In all the other cases, the message is ignored.

The default consent message is shown in the current user language, if available. To avoid showing mixed languages, use this parameter in conjunction with the language parameter.


Examples:
consent_message: 'You should also accept the site's <a href="https://example.com/rules">Privacy policy</a>'
Examples

Example of how to pass parameters to Now4real:

<script type="text/javascript">
  window.now4real = {};
  now4real.config = {
    target: 'api+widget',
    widget: {
      align: 'right',
      align_mobile: 'left',
      color_external_background: '#da3f3f',
      color_external_text: '#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 = {};
  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.

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.

PostOptions :object

An object that contains the options for the post call.

Properties:
Name Type Description
replyTo string

The id of the message to reply to.

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.

TypingList :Array.<User>

An array that represents the typing list.

getPollVotePayload :object

Properties:
Name Type Description
vote Array.<number>

An array of numbers indicating the indices of the poll options that the user has voted for.

loginPayload :object

Properties:
Name Type Description
user CurrentUser

The authenticated user.

persistent boolean

false if the custom authentication is being used or, in case of social login, 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.

mutePayload :object

Properties:
Name Type Description
expiration number

The number of milliseconds from the Unix Epoch to the time the user can post messages again into the pagechat or null if the user was muted forever.

onerrorCallback(error) → {void}

Parameters:
Name Type Description
error Now4realError

The error encountered while loading.

postPayload :object

Properties:
Name Type Attributes Description
waitPeriod number

The number of milliseconds to wait before sending another message on behalf of the logged-in user in the current pagechat. Sending a new message before this delay expires will result in an error.

suggestions Array.<string> <optional>

An optional list of suggestions returned by the configured chatbot webhook. These suggestions are available only if a chatbot is configured in the current pagechat and can be used to guide the next steps in the conversation with the chatbot.

subjectUpdateCallback(subjectUpdate) → {void}

Parameters:
Name Type Description
subjectUpdate Now4realSubjectUpdate

The object that contains the update data.