Javascript API
Viafoura aims to empower our customers to integrate and customize our community engagement platform. By using our JavaScript API we allow you to subscribe to our event bus to allow you to integrate with your own analytics platforms, or add custom behaviors on certain engagement events. You may want to listen for new comments, or likes being added.
Another common integration is done by publishing your own events onto our event bus to trigger UI elements such as our notification tray, or trigger a login flow.
VfUniqueId
The unique_id attribute allows multiple URLs to be linked to the same page and thus, comments
created under associated URLs will be the same. You may specify any string you would like to
use as your unique_id, as long as it is no more than 100 characters in length.
If used incorrectly, unique_ids can lead to problems such as comments for different pages showing
in the wrong places. As such we recommend exercising caution when utilizing this feature.
Viafoura unique ID documentation
Type: String
vf
The JavaScript API exposes a global variable (window.vf) to enable easy interaction
with the Viafoura JavaScript code running on your page.
It is best used in conjunction with vfQ to ensure your callbacks run
after the Viafoura context has fully loaded.
Examples
// Make vfQ available or use existing one if already loaded
window.vfQ = window.vfQ || [];
window.vfQ.push(() => {
// viafoura is loaded and window.vf is available
window.vf.context.get('user').then((user) => {
// log all the properties of the logged-in user
console.log(user);
});
});
$publish
$publish - publish an event to a dispatcher.
View the full list of events.
Parameters
channel
string channel event is taking place inevent
string name of eventargs
array arguments to pass to callbacks
Examples
window.vf.$publish('tray', 'open', 'args');
$subscribe
$subscribe - subscribe to an event through a dispatcher.
View the full list of events.
Parameters
channel
string channel of subscriptionevent
string event of subscriptioncallback
function callback when event occurs
Examples
window.vf.$subscribe('login', 'failure', function() {});
Returns EventSubscription subscription
$unsubscribe
$unsubscribe - unsubscribe from a channel/event combo through a dispatcher.
View the full list of events.
Parameters
Examples
window.vf.$unsubscribe('login', 'failure');
Returns array subscriptions unsubscribed from
$once
$once - subscribe once to a channel/event combo through a dispatcher.
View the full list of events.
Parameters
channel
string channel of subscriptionevent
string event of subscriptioncallback
function callback to call once when event is triggered
Examples
window.vf.$once('login', 'failure', function() {});
Returns EventSubscription one-time subscription
$prepublish
$prepublish - lifecycle hook to run before $publish invocation
Parameters
hook
function pre $publish function
Examples
window.vf.$prepublish((channel, event, ...args) => {
if (channel === 'authentication' && event === 'required') {
return false;
}
return { channel, event, args };
});
context
The vf.context API is used to manage the application context and state. This
is primarily useful when working with single page apps,
infinite scroll implementations
and other similar functionality.
get
Returns a promise resolving to a context item (either page, or user)
Parameters
key
PUBLIC_CONTEXTS context object being fetched
Returns Promise<(VfUser | VfPageMeta | VfNotifications)> resolves to a context object
teardown
This function is used to destroy the current viafoura context. It will:
- Unsubscribe from realtime events
- Destroy all widgets on the page
- Posts engagement tracking data to our analytics server
- Pauses window.vfQ
This function is intended to be used when you would like do perform some
intermediate actions between the teardown and setup steps of a page reset.
Parameters
shouldDestroyWidgets
Boolean If false, widgets attached to a VfContainer remain in the DOM and their event
listeners remain intact, if true, they are reverted to their original state before they were loaded as functioning components (optional, defaulttrue
)
Examples
// First destroy the current viafoura context
window.vf.context.teardown()
// Update the page meta information
.then(updatePageMetaData)
// Add some new widgets to the page
.then(addNewWidgetContainers)
// Finally restart the viafoura application
.then(window.vf.context.setup);
Returns Promise A promise resolving to nothing
setup
This function is used to initialize the viafoura application. It is used after
teardown to restart the viafoura application. It will:
- Refetch the page meta data
- Reloads all settings/page/user/language information
- Reinitialize all widgets
- Refire analytics
- Restarts window.vfQ
This function is intended to be used when you would like do perform some
intermediate actions between the teardown and setup steps of a page reset.
Examples
// First destroy the current viafoura context
window.vf.context.teardown()
// Update the page meta information
.then(updatePageMetaData)
// Add some new widgets to the page
.then(addNewWidgetContainers)
// Finally restart the viafoura application
.then(window.vf.context.setup);
Returns Promise A promise resolving to nothing
reset
vf.context.reset()
resets the Viafoura JavaScript, loading any changes
to the meta tags, or other properties defined after page initialization.
Conceptually, calling the vf.context.reset()
method is treated as a new
page load. As such, this call triggers a full re-initialization of our
engagement tools, which means several requests to our REST APIs will be invoked.
Call this if Viafoura should display new content when no page reload was
triggered. This function will return a promise which resolves when it is finished.
Custom behaviour after the reset is finished can be chained onto the promise.
The Viafoura reset function internally runs both vf.context.teardown
and vf.context.setup.
NOTE: any changes to the widget after they have been loaded
will not take effect after a viafoura reset. i.e. if you change
the data-path of the commenting widget, viafoura.reset will not action that change.
This change was made to accomodate our new widgets.
If you would still like to use reset to change a data-attribute, you can call
vf.context.teardown, perform changes and then vf.context.setup.
Returns Promise A promise resolving to nothing
setCurrentPage
It is used for an infinite scroll implementation. For more information on infinite scroll,
please refer to our infinite scroll implementations.
The first parameter is an element denoting a new page. The element passed in should be a wrapper containing all
the html for the newly loaded page. All widgets in the DOM that are within this parent element will be initialized
after calling this function.
Parameters
el
HTMLElement [options] - top level article container containing all the Viafoura widgets of this new page
Returns Promise<(VfPage | null)> A promise resolving after the page data has been successfully fetched. If fetchPage
is false
the promise resolves to null
.
resetWidget
vf.context.resetWidget()
. Takes in a widget DOM element and tears down that one widget and then re-registers all widgets. This is useful when you want to
rebuild only one widget on the page but do not want to reset everything.
This function will also send attention time tracking events because tearing down the widget will result in the engagement data being lost, so it
must be sent before it is destroyed.
NOTE: this will build any other unmounted widgets on the page
Parameters
widget
Element DOM element of widget being resetshouldDestroyWidget
boolean If false, widgets attached to a VfContainer remain in the DOM and their event
listeners remain intact, if true, they are reverted to their original state before they were loaded as functioning components (optional, defaulttrue
)
Returns Promise A promise resolving immediately
topics
The topics JS API is used to manage topic subscriptions on a page or for a user.
subscribe
Subscribe the current user to a topic.
Parameters
topic_id
String id of the topictopic_name
String name of the topictopic_type
String? type of topic. Default is "topic"store
Object? optional custom store (needed for tests)
Examples
window.vf.topics.subscribe("id", "topic");
Returns Promise promise that resolves when the topic subscription is complete
page
Fetch a list of all topics that have been set in the DOM of the current page
Examples
window.vf.topics.page()
.then((topics) => console.log(topics));
Returns Promise promise that resolves to the list of topics
unsubscribe
Unsubscribe current user from a topic.
Parameters
Examples
window.vf.topics.unsubscribe("id");
Returns Promise promise that resolves when the topic unsubscribe is complete
fetch
Fetch a list of topics that the current user already subscribes to.
Parameters
store
Object? optional custom store (needed for tests)
Examples
window.vf.topics.fetch()
.then((topics) => console.log(topics));
Returns Promise promise that resolves to an array of topics
isSubscribedTo
Check if the current user is subscribed to a given topic.
Parameters
topic_id
Object The id of the topic you are checking
Examples
window.vf.topics.isSubscribedTo(topic_id)
.then((isSubscribed) => console.log(isSubscribed));
Returns Promise promise that resolves to a Boolean
countTopic
Fetch a count of topics followers.
Parameters
topic_id
Object The id of the topic you are checkingstore
Object? optional custom store (needed for tests) (optional, defaultvuexStore.getInstance()
)
Examples
window.vf.topics.count(topic_id).then((count) => console.log(count));
Returns Promise promise that resolves to a Boolean
session
Object representing the current user session
Examples
window.vf.session;
logout
performs a viafoura logout
Examples
window.vf.session.logout();
Returns Promise promise that resolves when the logout is complete
login
viafoura login apis
loginRadius
login - attempts to login a LoginRadius account with the given access token
Parameters
token
String access token
Examples
window.vf.session.login.loginRadius("token")
Returns Promise login promise
jwt
performs a viafoura JWT login
Parameters
access
String a viafoura access token for a userrefresh
String a viafoura refresh token for a usersession
String a viafoura legacy session ID for a user
Examples
window.vfQ = window.vfQ || [];
window.vfQ.push(function() {
window.vf.session.login.jwt(access, refresh, session)
.then((user) => alert(`You are now logged in as ${user.name}`))
.catch((e) => alert(e.message));
});
Returns Promise promise that resolves to a user when the login is completeThe JWT login javascript function can be used to execute a login using an existing access/refresh token
pair as well as a legacy session ID. This will log in the user with Viafoura's servers and set any
necessary cookies and local state.See the full JWT login flow documentation for more information.
cookie
performs a viafoura cookie login
Parameters
cookie
String string representing the login cookie
Examples
window.vf.session.login.cookie("token");
Returns Promise promise that resolves when the login is completeThe Cookie Login javascript function can be used to execute the Cookie Login Integration on pages that have
Viafoura engagement modules present like the Commenting Module. This javascript function requires your
Cookie Login Integration to be completed.View the full cookie login documentation.
social
performs a legacy viafoura social login
Parameters
type
String string representing network to socially login from
Examples
window.vf.session.login.social("facebook");
Returns Promise promise that resolves when the login is complete
PUBLIC_CONTEXTS
The various context objects that can be accessed from the Viafoura JS API
Type: enum
Properties
user
String Specify the "user" contextpage
String Specify the "page" contextnotifications
String Specify the "notification" context
USER_PRIVILEGE
Viafoura user privilege levels:
Type: enum
Properties
guest
String Guest user privileges. Can only view but cannot take any actions (A guest user can post comments if anonymous comments are enabled)user
String Regular user privileges. Can perform regular user actions (e.g. post comment, like, follow)moderator
String Moderator user privileges. Can perform moderation actions (e.g. approve, disable)administrator
String Administrator user privileges. Can perform administrative actions (e.g. promote, demote)
Example
window.vf.context.get('user').then((user) => {
if(user.user_privilege == "guest"){
//not logged in
}
});
vfQ
The window.vfQ api provides a safe mechanism for executing functions which
depend on the viafoura context and API. Because the API is loaded asynchronously
there is a need to have a method to queue functions to run once the Viafoura
context is fully loaded.
Examples
// Safely initialize vfQ
window.vfQ = window.vfQ || [];
// add callbacks to vfQ
window.vfQ.push(() => console.log('window.vf.* is now ready'));
VfPage
A Viafoura page object describing attributes that define a page
Type: Object
Properties
date_created
Number The page creation datedate_expires
Number The date that comments will be closed on this pagedescription
String The description for the pagefull_page_url
String The fully qualified url of the page (eg: <<https://foo.com/mypage.html?2345=abc#hash>>)host
String host of the pageid
Number A Viafoura page idimage_url
String The page image urlnum_replies
Number The number of replies on the pagepath
String The path of the page (eg: /mypage.html?2345=abc#hash)section_id
Number The section id of the pagesite_id
Number The site if of the pagestatus
Boolean Status of the pagetitle
String The page's title
BAN_LEVELS
Viafoura user ban levels:
Type: enum
Properties
posting
String Disables the users from submitting any new comments or replies. They will be able to do other engagement activities (likes, follow, report, etc).ghost
String User is able to perform all normal actions, but their comments and replies are only visible to themselves and moderators.login
String Disabled the user from logging in and performing all actions that require authentication (like, dislike, report, etc).hide
String In addition to banning the user, this will ensure all their posts are hidden from view of other users.none
String User is not banned.
VfUser
This is a viafoura user
Type: Object
Properties
uuid
Uuidid
Numbername
Stringemail
Stringuser_privilege
USER_PRIVILEGESban_level
BAN_LEVELScustom_badges
Array<Object>date_created
Numbersubscriber_count
Numberemail_verification_status
ModerationStatususername_moderation_status
ModerationStatusavatar_moderation_status
ModerationStatuspic_small
Stringpic_large
Stringdata_count
Function
Examples
{
uuid: "00000000-0000-4000-8000-00e8d4a52092"
id: 1000000004242,
name: "Viafoura User",
email: "[email protected]",
user_privilege: "user",
ban_level: "none",
custom_badges: [],
date_created: 1611772566000,
subscriber_count: 0,
email_verification_status: "none",
username_moderation_status: "none",
avatar_moderation_status: "none",
pic_large: "https://s3.amazonaws.com/viafoura/user_pictures/1000000004242_5_120x120.jpg",
pic_small: "https://s3.amazonaws.com/viafoura/user_pictures/1000000004242_5_60x60.jpg",
data_count: function () {},
}
user.data_count().then(data_count => console.log(data_count));
// Output: { comments_made: 0, dislikes_made: 0, dislikes_received: 0, likes_made: 0, likes_received: 0 }
VfNotifications
The viafoura Notifications object contains information about the current user's
notifications
Type: Object
Properties
counts
Object A collection of notification countscounts.new
Number The number of "new" (unseen) notifications, as shown in the Viafoura bell
VfPageMeta
A Viafoura page meta object describing page attributes for fetching/creating pages
One of path, url, id, or unique_id is required - path and url are mutually exclusive
Title, section are optional
Type: Object
Properties
path
String? The path of the page (eg: /mypage.html?2345=abc#hash)url
String? The fully qualified url of the page (eg: <<https://foo.com/mypage.html?2345=abc#hash>>)unique_id
VfUniqueId? The unique id of the pageid
Number? A Viafoura page idtitle
String? The page's titlesection
String? The section name for the page
Updated 5 months ago