| [ Web Proxy ] |
| Viewing: https://documentation.viafoura.com/docs/javascript | [Back] [Original] |
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.
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
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 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 callbacksExamples
window.vf.$publish('tray', 'open', 'args');$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 occursExamples
window.vf.$subscribe('login', 'failure', function() {});Returns EventSubscription subscription
$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 - 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 triggeredExamples
window.vf.$once('login', 'failure', function() {});Returns EventSubscription one-time subscription
$prepublish - lifecycle hook to run before $publish invocation
Parameters
hook function pre $publish functionExamples
window.vf.$prepublish((channel, event, ...args) => {
if (channel === 'authentication' && event === 'required') {
return false;
}
return { channel, event, args };
});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.
Returns a promise resolving to a context item (either page, or user)
Parameters
key PUBLIC_CONTEXTS context object being fetchedReturns Promise<(VfUser | VfPageMeta | VfNotifications)> resolves to a context object
This function is used to destroy the current viafoura context. It will:
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 aVfContainer remain in the DOM and their eventtrue)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<null> A promise resolving to nothing
This function is used to initialize the viafoura application. It is used after
teardown to restart the viafoura application. It will:
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<null> A promise resolving to nothing
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<null> A promise resolving to nothing
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 pageReturns Promise<(VfPage | null)> A promise resolving after the page data has been successfully fetched. If fetchPage is false the promise resolves to null.
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 aVfContainer remain in the DOM and their eventtrue)Returns Promise A promise resolving immediately
The topics JS API is used to manage topic subscriptions on a page or for a user.
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
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 current user from a topic.
Parameters
Examples
window.vf.topics.unsubscribe("id");Returns Promise promise that resolves when the topic unsubscribe is complete
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
Check if the current user is subscribed to a given topic.
Parameters
topic_id Object The id of the topic you are checkingExamples
window.vf.topics.isSubscribedTo(topic_id)
.then((isSubscribed) => console.log(isSubscribed));Returns Promise promise that resolves to a Boolean
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, default vuexStore.getInstance())Examples
window.vf.topics.count(topic_id).then((count) => console.log(count));Returns Promise promise that resolves to a Boolean
Object representing the current user session
Examples
window.vf.session;performs a viafoura logout
Examples
window.vf.session.logout();Returns Promise promise that resolves when the logout is complete
viafoura login apis
login - attempts to login a LoginRadius account with the given access token
Parameters
token String access tokenExamples
window.vf.session.login.loginRadius("token")Returns Promise login promise
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 userExamples
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.
performs a viafoura cookie login
Parameters
cookie String string representing the login cookieExamples
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.
performs a legacy viafoura social login
Parameters
type String string representing network to socially login fromExamples
window.vf.session.login.social("facebook");Returns Promise promise that resolves when the login is complete
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" contextViafoura 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
}
});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'));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 titleViafoura 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.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 FunctionExamples
{
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 () {},
}
DeprecatedSome values on the user object (comments_made, dislikes_made, dislikes_received, likes_made, likes_received) are deprecated. Use the following API's to get user content stats:
Comments: https://documentation.viafoura.com/reference/getuserprofile-2
Live blogs: https://documentation.viafoura.com/reference/getuserprofile
Live Chats: https://documentation.viafoura.com/reference/getuserprofile-1
Ratings & Reviews: https://documentation.viafoura.com/reference/getuserprofile-3
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 }The viafoura Notifications object contains information about the current user's
notifications
Type: Object
Properties
counts Object A collection of notification counts
counts.new Number The number of "new" (unseen) notifications, as shown in the Viafoura bellA 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 pageUpdated 11 months ago
| Web Proxy Viewer | New URL | Original Page |