Enter fullscreen mode

How to get the login name of the current user using JavaScript?

But I got an alert and it shows «[object object]». How to get the loginName of current user? Any help appreciated.

6 Answers 6

If you are working on SharePoint Online, then they have introduced a new variable to hold the current user’s login name in the _spPageContextInfo global object.

_spPageContextInfo.userLoginName; 

This will get you the login name without making any AJAX calls with JSOM or REST.

I just tried that in 2013 and it’s undefined. SharePoint Online here. _spPageContextInfo.userId works, though, and is a good starting point.

function GetCurrentUsername() < var ctx = new SP.ClientContext.get_current(); this.website = ctx.get_web(); this.currentUser = website.get_currentUser(); ctx.load(currentUser); ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFail)); >function onSuccess(sender, args) < alert(currentUser.get_loginName()); >function onFail(sender, args)

It shows [object object] in your alert message because you are trying to display an object instead of its properties. [Object object] is the default serialization of an object in JavaScript.

You can use JSOM or REST API to get current user as follows

 function getCurrentUser() < var context = new SP.ClientContext.get_current(); var web = context.get_web(); currentUser = web.get_currentUser(); context.load(currentUser); context.executeQueryAsync(onSuccess, onFail); >function onSuccess(sender, args) < var acountname = currentUser.get_loginName(); // extract the login name from the account name // var username = currentUser.get_title(); >function onFail(sender, args)

using REST API // for SharePoint 2013

function getUser() < var userid = _spPageContextInfo.userId; // alert(userid); var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")"; var requestHeaders = < "accept": "application/json;odata=verbose" >; $.ajax(< url: requestUri, contentType: "application/json;odata=verbose", headers: requestHeaders, success: onSuccess, error: onError >); function onSuccess(data, request) < var loginName = data.d.Title; alert(loginName); >function onError(error) < alert("Error on retrieving current user."); >> 

You never load any objects and never executes the query so there is no wonder you get an error.

var clientContext = SP.ClientContext.get_current(); var website = clientContext.get_web(); currentUser = website.get_currentUser(); clientContext.load(website); clientContext.load(currentUser); clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed); function onRequestSucceeded() < alert(currentUser.LoginName); >function onRequestFailed(sender, args)

Where website and currentUser are declared in the outer function (encapsuling the onRequestSucceeded method)

With reservation for errors in the code (are writing this from my phone)

Источник

Get More Data About a User with JavaScript Variable

In one of my previous blog posts, I’ve explained what is JavaScript variable in Google Tag Manager and how to use it. This time, I thought I’d give you more examples where you can apply it.

Currently, my courses are hosted on Teachable. I decided that I don’t want to spend my time building and hosting some custom solutions, therefore, I chose a ready-made platform.

Even though Teachable offers a built-in Google Analytics tracking, I’m not happy with it as I did not manage to make it work together with a cookie consent mechanism. In other words, the built-in GA functionality fires regardless of user’s/visitor’s privacy preferences.

Читайте также:  Vmware horizon view html access

That’s why I’m doing some generic tracking myself with GTM there. By doing that, I came up with an idea for this blog post: did you know that it’s fairly easy to obtain logged in user’s data (e.g. user ID) with JS variable? The knowledge of this possibility becomes very useful when a developer is super busy (or unavailable) and cannot push user data to the Data Layer.

Before we continue

This guide will not be one of those where “copy-paste” will work. Every website/web app has its own unique structure, therefore, what works on one site, might not work on another.

The goal of this blog post is to show you the possibility and the workflow to make this technique work. However, there is always a chance of failure.

Also, this topic is thoroughly explained in my Intermediate Google Tag Manager course. So if you prefer video content and you want to learn many other cool features/tricks/tips in Google Tag Manager, consider enrolling.

Enroll in Intermediate Google Tag Manager course

What is JavaScript Variable?

A quick refresher. If you haven’t read it, please go and check this guide first.

Before we start digging deeper, you need to learn about the scope. In JavaScript, there are two types of scope:

Variables declared within a JavaScript function, become LOCAL to the function, meaning that they are not accessible (visible) from outside the function. Take a look at the example below:

// code here can not use authorName variable function myFunction() < var authorName = "Julius"; // code here can use authorName variable >

There is a variable authorName and it only can be accessed within the function called myFunction.

Contrary to that, a variable declared outside a function becomes GLOBAL. A global variable has global scope: all scripts and functions on a web page can access it. Let’s use the same code example but place the variable outside the function.

// code here can use authorName variable var authorName = "Julius"; function myFunction() < // code here can use authorName variable >

What does it have to do with the JavaScript Variable in Google Tag Manager? Well, it can fetch the values of any global variable which is present at that moment.

So what?

Usually, user ID or some other data is often stored in global JavaScript variables. You just need to find it. Be aware, that sometimes the search of particular variables might be really time-consuming to do that and even might end up in achieving absolutely nothing.

But it’s definitely worth a shot 🙂 Also, if you can reach out to a developer, you can ask him/her what is global JS variable where the user ID stored (or maybe some other useful data is available as well?). Giving the answer should not be time-consuming for a dev.

Search for the right Global Variable(s)

To start the search, go to the developer console of your browser (here’s the tutorial on how to do that on Chrome), type window and hit enter (like in the screenshot below).

Читайте также:  background-repeat

window in console

Click the black triangle near the Window and you’ll see a list of properties that we’ll be able to access with a JavaScript Variable in GTM. Brace yourself, that list will be huge.

global js variables

Let’s go back to my Teachable’s example. I know that previously Teachable was known as Fedora. So my guess would be to keep looking for variables somehow related to either Teachable or Fedora.

Let’s start playing a detective. Bingo, I see 3 variables related to Fedora:

fedora variables

Since I’m currently interested in user data, I’ll click the black triangle next to fedora_user to expand it. Bingo, there’s a bunch of data that I could possibly use, for example, ID, name, etc.

User data in Teachable

Just a friendly reminder: email and name must not be sent to Google Analytics because this data is PII (personally identifiable information). But maybe you plan to send it to some other tool which allows it? Another friendly reminder: you need to get consent from your users/visitors to process this personal information (due to GDPR).

Personally, I don’t plan to use this data in my generic tracking but I wanted to show you what’s under the hood and what you can do.

Create JavaScript variables in Google Tag Manager

Next, let’s create those variables in GTM. Go to Variables > New and choose JavaScript Variable. For each data point you’ll need to create a separate JS variable:

Here’s an example of User ID variable. Let’s remember how we found that data point in the developer’s console. First, we clicked fedora_user and then id. So the value that we need to enter in the JavaScript variable (in GTM) is fedora_user.id (every level needs to be separated by a dot).

fedora user id

Save the variable and check whether it’s properly fetched. Refresh the GTM Preview and Debug mode, then go to the website you’re working on and refresh it as well.

In Preview and Debug console, go to Variables and check that JS variable you’ve just created. If it’s undefined, you’ve entered something wrong (maybe some typo?).

JS variable in GTM preview and debug mode

More examples

Keep in mind that the path to the correct variable will be different on most websites/web applications because the naming convention solely depends on developers (there are no widely accepted standards). For example, in one of the projects that I worked on, user ID’s path was app.id, which is super generic. But there’s nothing you can do about it, you can either adapt to it or do nothing at all.

Here’s a couple of more examples to give you a better understanding of where to keep looking for useful data:

Prestashop data

  • In Prestashop 1.7, (when a user is logged in) you can go to prestashop property and see for yourself what you can use. In this example, unfortunately, I don’t see an ID anywhere, but there are some other possibly useful data points. So if I was interested in, say, the first name, its path would be prestashop.customer.firstname
  • In Shopify, there are several options how to get logged in user’s ID:
    • ShopifyAnalytics.meta.page.customerId
    • or __st.cid
Читайте также:  Css span padding bottom

You’re probably wondering how could I possibly know where to find the user ID on Shopify? Listen very carefully, I’m about to share with you my super secret never-heard-before unique method: I googled it.

using google to find the answer

People have offered several options there. The fastest way to check whether the suggestion is working or not is to copy that suggested variable (e.g. ShopifyAnalytics.meta.page.customerId), paste it to browser’s developer console and hit enter. If you get an error, that’s not going to work. If you get the actual value, cha-ching!

Final words

In this blog post, I’ve explained a trick that I sometimes apply in my projects when a developer is not available. However, this solution is not fail-proof. If a developer changes the name of any variable in the path (that you entered in the JavaScript variable in GTM), the implementation will break. If a developer changes the data structure, this method will also fail.

So if possible, always try to get the developer to push the user data to the Data Layer. But if that’s not possible, you’ve just learned one more option.

Источник

How to get user IP address, location, and device info using JavaScript in browser

JavaScript is not able to get user IP address when running in browser. However, it is possible to do that with a server-side API call. With an API service called VisitorAPI, you can make it happen in just a couple lines of JavaScript. VisitorAPI returns the user’s IP address, location, currencies, languages, and device info with a REST API call. The following code loads the API:

var VisitorAPI=function(t,e,a),s.open("GET","https://visitorapi-dev.uc.r.appspot.com/api/?pid highlight__panel js-actions-panel"> 

Once the API is loaded, you can make an API call with the following syntax:

new VisitorAPI(projectID, successHandler, errorHandler); 

  • projectID: This is unique identifier of your VisitorAPI project which you can create in VisitorAPI UI for free.
  • successHandler: This is a function that process the visitor data when the API call is successfully. See response data format here.
  • errorHandler: This is a function that handles the error code and error message when the API call returns an error. The function can have two parameters: error code and error message.

Below is an example to print the user data in browser console:

VisitorAPI( "om61tWZOjuBBPxTdDlpy", function(data), function(errorCode, errorMessage) ); 

It will print a JSON object similar to the example below based on the current user's real IP address and device data.

It is important to note that VisitorAPI doesn't use API key to authenticate your API calls, because any API keys would be exposed to the public and that defeats the purpose of the keys. Instead, it allows you to put in an authorized domain list that are allowed to call the API endpoint from, so that no one else is able to call your API endpoint and use your API quota.

Источник

Оцените статью