Using sp.js functions outside of sharepoint - javascript

I'm trying to get the users information name and Email from sharepoint using their JS library. I have managed to do so however, i have the home page for this website on a local server running an Apache web server due to my need for PHP (For MySql Database Query). I thought about passing the information through the URL but the realisation that the homepage is linked on every single page 1000+ pages and having to add this to every page would be daunting, primarily because of Sharepoints horrid upload system. I will list the code that i used on the sharepoint site.
Script Tags:
<script src="/_layouts/15/init.js"></script>
<script src="/_layouts/15/MicrosoftAjax.js"></script>
<script src="/_layouts/15/ScriptResx.ashx?name=sp.res&culture=en-us"></script>
<script src="/_layouts/15/sp.runtime.js"></script>
<script src="/_layouts/15/SP.Core.js"></script>
<script src="/_layouts/15/sp.js"></script>
JS Code:
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init()
{
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
function onQuerySucceeded()
{
var username = currentUser.get_title();
var useremail = currentUser.get_email();
if (typeof(Storage) !== "undefined")
{
localStorage.setItem("userName", username);
localStorage.setItem("email", useremail);
document.getElementById("userTitle").innerHTML = username;
document.getElementById("userEmail").innerHTML = useremail;
var urlString = "URL Censored?username=" + username + "&email=" + useremail;
window.location = (urlString);
}
}
function onQueryFailed(sender, args)
{
alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
HTML Display Code:
<div class="information">
<span id="userTitle"></span></br>
<span id="userEmail"></span></br>
</div>
CSS:
.information
{
position: absolute;
top: 10px;
right: 10px;
color: white;
}
I will not claim this JavaScript as my own. I am primarily a Java dev. I've only started making this website recently. (4 Months or so) Any help understanding this would be much appreciated. Putting forth alot of effort to learn this in hopes of being where i am in Java at one point.

Related

How do I integrate google sign in to my website and collect the users details?

I want to integrate the google sign in button onto my website. I know html but I am unsure on php and java script. Ultimately, I would like the google sign in to sign in the user and give me their information so i can store it on my database on phpmyadmin securely. I have visited the google tutorial for this but found it did not explain how to collect the users information fully. I have attempted to follow this and so far I have this but it is far from what it should be like. I have watched other tutorials such as this one. However i find they all do not follow the googles instructions as for example you have to download a google API in them, however on the google website it does not mention downloading anything.
Below is the code of what i have managed to do so far by using the google tutorial:
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="808271051181-424qcdq0emrd0pd77frfiuacvcetp58t.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
</body>
</html>
You might be able to get all data from the profile in javascript, but I wanted to get all their data into php variables so that I could store in my database. To do this I sent the google id token as post data from javascript (how to do that here).
You still need all the other google sign in code you have, but I replaced onSingIn with this:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
document.getElementById("userid").value = googleUser.getAuthResponse().id_token;
document.getElementById("userid").form.submit();
}
Also add the form code in the body:
<form action="login.php" method="post">
<input type="hidden" name="id" id="userid">
</form>
You then need another file I called it login.php which contains the following function:
function get_var($var)
{
$id = $_POST["id"]; // id from google
$id_token = file("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $id); // decrypted id
foreach ($id_token as $part) {
// part is a factor of the user such as name or email
// remove unecessary charcters
$peice = str_replace("\"", "", $part);
$peice = str_replace(",", "", $peice);
$peice = substr($peice, 0, strpos($peice, ":") + 2);
if (strpos($peice, $var) !== false) {
$var = str_replace("\"", "", $part);
$var = str_replace(",", "", $var);
$var = substr($var, strpos($var, ":") + 2);
return $var;
}
}
}
With this you should be able to get all the information you need. Example uses:
$name = trim(get_var("name"));
$email = trim(get_var("email"));
To view all the accessible information either print out $id_token in get_var or go to https://www.googleapis.com/oauth2/v3/tokeninfo?id_token= adding an id token at the end.
More information about getting data from an ID token here.

Extract email address from Google account

I'm working on a website where the client has asked for an option to allow signup/login using Google and Facebook accounts. How can I extract the email address from a user's Google profile for storing in database?
Here is my code. The problem is that I am not getting the user profile completely. Instead, I am receiving just user name.
try
{
WebClient client = new WebClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ access_token;
string outputData = client.DownloadString(urlProfile);
GoogleUserOutputData serStatus =
JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
return serStatus;
// You will get the user information here.
}
}
catch (Exception ex)
{
//catching the exception
}
return null;
Here is a way to receive data (email, etc.) in JavaScript. At the end it shows an alert with data. (You can store this data in a database.) It's a complete working example with a Google button.
<html>
<head>
<title>Demo: Getting an email address using the Google+ Sign-in button</title>
<!-- Include the API client and Google+ client. -->
<script src = "https://plus.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<!-- Container with the Sign-In button. -->
<div id="gConnect" class="button">
<button class="g-signin"
data-scope="email"
data-clientid="Your_Client_ID"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
<!-- Textarea for outputting data -->
<div id="response" class="hide">
<textarea id="responseContainer" style="width:100%; height:150px"></textarea>
</div>
</div>
</body>
<script>
/**
* Handler for the signin callback triggered after the user selects an account.
*/
function onSignInCallback(resp) {
gapi.client.load('plus', 'v1', apiClientLoaded);
}
/**
* Sets up an API call after the Google API client loads.
*/
function apiClientLoaded() {
gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
}
/**
* Response callback for when the API client receives a response.
*
* #param resp The API response object with the user email and profile information.
*/
function handleEmailResponse(resp) {
var primaryEmail;
var name;
var gender;
for (var i=0; i < resp.emails.length; i++) {
if (resp.emails[i].type === 'account')
primaryEmail = resp.emails[i].value;
if (resp.displayName != null)
name = resp.displayName;
gender = resp.gender;
}
document.getElementById('responseContainer').value = 'Primary email: ' +
primaryEmail + '\n\nFull Response:\n' + JSON.stringify(resp);
ShowAlert("Email: "+primaryEmail +" "+"Name: "+ resp.displayName +" "+"Gender: "+gender);
}
</script>
</html>
For further information and detail you can (should) read this link:
Getting people and profile information
Documentation is the key; please check it completely.
https://developers.google.com/identity/sign-in/web/sign-in
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}
Sign out
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>

Linkedin shows 403 forbidden error in java script api

I am trying to search people with company name but it displays in console as
GET https://api.linkedin.com/v1/people-search:(num-results,people:(first-name,last-name,distance))?company-name=infosys 403 (Forbidden) xdrpc.html?v=0.0.2000-RC8.35784-1413:1651
My Code :
<html>
<head>
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: --api-key-here--
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad() {
alert("authenticating..");
// Listen for an auth event to occur
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
IN.API.PeopleSearch()
.fields("firstName", "lastName", "distance")
.params({"company-name":"infosys"})
.result(displayPeopleSearch)
.error();
}
function displayPeopleSearch(peopleSearch){
var peopleSearchDiv = document.getElementById("peoplesearch");
var members = peopleSearch.people.values;
for (var member in members) {
// but inside the loop, everything is the same
// extract the title from the members first position
peopleSearchDiv.innerHTML += "<p>" + members[member].firstName + " " + members[member].lastName + " is a " + members[member].positions.values[0].title + ".</p>";
}
}
</script>
</head>
<!-- need to be logged in to use Search; if not, offer a login button -->
<script type="IN/Login"></script>
<body>
</body>
</html>
Found after a big battle,Linked IN has created vetted API access to people search only developers registered to that process can Access people search function

Redirecting to the root using javascript

In my project I have the following script in order to open a page:
<script type="text/javascript">
function setPage(pName) {
var iPage = "'" + pName + "'";
document.getElementById('iFrame').src = window.location.href(iPage);
}
</script>
when I run the program it gives me the following problematic url:
Requested URL
http://localhost:7819/Pages/Account/'http:/localhost:7819/Pages/Support/Asp/Help01.aspx'
As we see the address contain the url of the current page plus the requested url.
More of it I'm loosing the second slash / in http:/ which I have it all the way inside the script.
How can I solve this issue?
I assume, you wanted something like this?
<script type="text/javascript">
function setPage(pName) {
document.getElementById('iFrame').src = pName;
}
</script>

canvg is undefined error

I am trying to use the code from Battlehorse to convert A Google Visualization chart to an image to save to a server. I was able to get this to work on localhost but when I attempt to use it on the Web Server I get the error "canvg is undefined". The Web Server is running IIS 7. I have searched quite a bit and have not been able to find any information regarding this error. Does anyone know what causes this error or how to resolve it?
http://www.battlehorse.net/page/topics/charts/save_google_charts_as_image.html
Code Sample:
<html>
<head>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script type="text/javascript">
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;}
function alert10() {
try {
var textbox1 = document.getElementById('textbox1');
textbox1.value = getImgData(document.getElementById('chart1_div'));
}
catch (err) {
alert(err.message);
}
}
</script>
</head>
I figured it out. The problem was that the site was running with SSL enabled and I was calling external script files by http protocols. I had to adjust the external script file references to either use https OR change them to relative like this:
<script type="text/javascript" src="//canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="//canvg.googlecode.com/svn/trunk/canvg.js"></script>
Using the protocol relative path like "//..." makes sure it will work in both HTTP and HTTPS

Categories