Customize ECB menu of Sharepoint hosted add-in - javascript

How could I hide some menu items from a ECB menu in a Sharepoint add-in, based on permissions? My Sharepoint application is Sharepoint hosted not provider hosted, so the javascript injection method wouldn't work.
Thanks

Function to check if user is member of specified group
function IsCurrentUserMemberOfGroup(groupName, OnComplete) {
var currentContext = new SP.ClientContext.get_current();
var currentWeb = currentContext.get_web();
var currentUser = currentContext.get_web().get_currentUser();
currentContext.load(currentUser);
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
var group = allGroups.getByName(groupName);
currentContext.load(group);
var groupUsers = group.get_users();
currentContext.load(groupUsers);
currentContext.executeQueryAsync(OnSuccess,OnFailure);
function OnSuccess(sender, args) {
var userInGroup = false;
var groupUserEnumerator = groupUsers.getEnumerator();
while (groupUserEnumerator.moveNext()) {
var groupUser = groupUserEnumerator.get_current();
if (groupUser.get_id() == currentUser.get_id()) {
userInGroup = true;
break;
}
}
OnComplete(userInGroup);
}
function OnFailure(sender, args) {
OnComplete(false);
}
}
usage
function IsCurrentUserHasContribPerms()
{
IsCurrentUserMemberOfGroup("Members", function (isCurrentUserInGroup) {
if(isCurrentUserInGroup)
{
// The current user is in the [Members] group!
}
});
}
ExecuteOrDelayUntilScriptLoaded(IsCurrentUserHasContribPerms, 'SP.js');
Source from here

thank you for your help. Finally I've got what I wanted to customize in my page. I've overriden the CreateMenuOption in core.js by creating another file (I've used Chrome to get the code). I've used the following js file too : https://spservices.codeplex.com/ in order to get the group of the connected user.

Related

Why doesn't this chrome extension work?

I want to collect the url (var name is 'url') of a webpage into a variable in a chrome extension, together with several user inputs in text inputs, and to send it to a remote php script for processing into an sql database. I am using AJAX to make the connection to the remote server. The popup.html contains a simple form for UI, and the popup.js collects the variables and makes the AJAX connection. If I use url = document.location.href I get the url of the popup.html, not the page url I want to process. I tried using chrome.tabs.query() to get the lastFocusedWindow url - the script is below. Nothing happens! It looks as though it should be straightforward to get lastFocusedWindow url, but it causes the script to fail. The manifest.json sets 'tabs', https://ajax.googleapis.com/, and the remote server ip (presently within the LAN) in permissions. The popup.html has UI for description, and some tags. (btw the response also doesn't work, but for the moment I don't mind!)
//declare variables to be used globally
var url;
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
// Change the value of the outputText field THIS PART IS NOT WORKING YET
function setOutput(){
if(httpObject.readyState == 4){
//document.getElementById('outputText').value = httpObject.responseText;
"Bookmark added to db" = httpObject.responseText; // does this work?
}
}
//put URL tab function here
chrome.tabs.query(
{"active": true, "lastFocusedWindow": true},
function (tabs)
{
var url = tabs[0].url; //may need to put 'var' in front of 'url'
}
);
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
//get url? THIS IS OUTSTANDING - url defined from chrome.tabs.query?
description = document.getElementById('description').value;
tag1 = document.getElementById('tag1').value;
tag2 = document.getElementById('tag2').value;
tag3 = document.getElementById('tag3').value;
tag4 = document.getElementById('tag4').value;
httpObject.open("GET", "http://192.168.1.90/working/ajax.php?url="+url+"&description="+description+"&tag1="+tag1+"&tag2="+tag2+"&tag3="+tag3+"&tag4="+tag4, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput(); //THIS PART IS NOT WORKING
finalString = httpObject.responseText; //NOT WORKING
return finalString; //not working
} //close if
} //close doWork function
var httpObject = null;
var url = null;
var description = null;
var tag1 = null;
var tag2 = null;
var tag3 = null;
var tag4 = null;
// listens for button click on popup.html
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', doWork);
});
Having no responses I first used a bookmarklet instead. The bookmarklet passes the url and title to a php script, which enters them into a db before redirecting the user back to the page they were on.
javascript:(function(){location.href='http://[ipaddress]/bookmarklet.php?url='+encodeURIComponent(location.href)+'&description='+encodeURIComponent(document.title)})()
Then I found this code which works a treat.
var urlOutput = document.getElementById('bookmarkUrl');
var titleOutput = document.getElementById('bookmarkTitle');
if(chrome) {
chrome.tabs.query(
{active: true, currentWindow: true},
(arrayOfTabs) => { logCurrentTabData(arrayOfTabs) }
);
} else {
browser.tabs.query({active: true, currentWindow: true})
.then(logCurrentTabData)
}
const logCurrentTabData = (tabs) => {
currentTab = tabs[0];
urlOutput.value = currentTab.url;
titleOutput.value = currentTab.title;
}

cordova-plugin-sms exec proxy not found

Hello I'm new in App development and I'm using cordova sms plugin to be able to auto send sms on button press. I followed the instructions carefully in this link https://www.npmjs.com/package/cordova-plugin-sms but it keeps saying exec proxy not found::SMS::sendSMS
Here's my code:
function sendSMS() {
var sendto = "+1234";
var textmsg = "MESSAGE";
if(sendto.indexOf(";") >=0) {
sendto = sendto.split(";");
for(i in sendto) {
sendto[i] = sendto[i].trim();
}
}
if(SMS) SMS.sendSMS(sendto, textmsg,
function()
{
alert('Success');
},
function(str)
{
alert(str);
});
}

Background task for push notifications on Windows Phone 8.1

I'm trying to register a background task on my Windows Phone 8.1 to receive and handle push notifications.At the moment everything is working when the app is opened (foreground+background), but a background task that is defined in the app.js does not work when app is closed.
This is defined in the package.phone.appxmanifest:
<Extension Category="windows.backgroundTasks" StartPage="js/lib/backgroundTask.js">
<BackgroundTasks>
<Task Type="pushNotification" />
</BackgroundTasks>
</Extension>
backgroundTask.js
(function () {
//var backgroundTask = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current,
//taskName = backgroundTask.task.name;
Windows.Storage.ApplicationData.current.localSettings.values["hello"] = "world";
close();
})();
this is what my app.js does:
var taskName = "mySuperFancyBgTaskName";
var registerBackgroundTask = function() {
var btr = Windows.ApplicationModel.Background.BackgroundTaskRegistration;
var iter = btr.allTasks.first();
var taskRegistered = false;
while (iter.hasCurrent){
var ta = iter.current.value;
if (ta.name == taskName){
taskRegistered = true;
break;
}
iter.moveNext();
}
if (!taskRegistered){
var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
var trigger = new Windows.ApplicationModel.Background.PushNotificationTrigger();
builder.setTrigger( trigger );
builder.taskEntryPoint = "js\\lib\\backgroundTask.js";
builder.name = taskName;
try{
var task = builder.register();
//task.addEventListener("completed", onPushNotification);
}
catch (e){
console.error(e);
}
}
}
var channel;
var pushNotificationManager = Windows.Networking.PushNotifications.PushNotificationChannelManager;
var channelOperation = pushNotificationManager.createPushNotificationChannelForApplicationAsync();
channelOperation.then(function (newChannel) {
channel = newChannel;
saveChannelUriInSettings(channel.uri);
console.log("opened push notification channel with uri: " + channel.uri);
registerBackgroundTask();
},
function (error) {
console.log("Channel could not be retreived. " + error.number)
}
);
It seems that backgroundTask.js is never started,because there is nothing written in the localsettings. Tried to do some stuff there, but of course not able to debug there.
If I do
var onPushNotification = function (e) { ...}
channel.addEventListener("pushnotificationreceived", onPushNotification);
receiving raw push notifications works fine. So how do I get backgroundtask to work, so that it can save incoming push notifications? If it is working there is no need to define a event listener in the app to catch push notifications, right?
Any help is appreciated - thanks in advance!

xpages JSON-RPC Service handling response from callback funciton

I have a slickgrid screen (on regular Domino form) wherein user can select and update some documents. I needed to show a pop-up displaying status of every selected document so I created an XPage. In my XPage I am looping through selected documents array (json) and call an RPC method for every document. Code to call RPC method is in a button which is clicked on onClientLoad event of XPAGE. RPC is working fine because documents are being updated as desired. Earlier I had RPC return HTML code for row () which was being appended to HTML table. It works in Firefox but not in IE. Now I am trying to append rows using Dojo but that’s not working either.
Here is my Javascript code on button click.
var reassign = window.opener.document.getElementById("ResUsera").innerHTML;
var arr = new Array();
var grid = window.opener.gGrid;
var selRows = grid.getSelectedRows();
for (k=0;k<selRows.length;k++)
{
arr.push(grid.getDataItem(selRows[k]));
}
var tab = dojo.byId("view:_id1:resTable");
while (arr.length > 0)
{
var fldList = new Array();
var ukey;
var db;
var reqStatusArr = new Array();
var docType;
var docno;
ukey = arr[0].ukey;
db = arr[0].docdb;
docType = arr[0].doctypeonly;
docno = arr[0].docnum;
fldList.push(arr[0].fldIndex);
reqStatusArr.push(arr[0].reqstatusonly);
arr.splice(0,1)
for (i=0;i < arr.length && arr.length>0;i++)
{
if ((ukey == arr[i].ukey) && (db == arr[i].docdb))
{
fldList.push(arr[i].fldIndex);
reqStatusArr.push(arr[i].reqstatusonly);
arr.splice(i,1);
i--;
}
}
console.log(ukey+" - "+db+" - "+docno+" - "+docType);
var rmcall = faUpdate.updateAssignments(db,ukey,fldList,reassign);
rmcall.addCallback(function(response)
{
require(["dojo/html","dojo/dom","dojo/domReady!"],function(html,dom)
{
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
html.set(tbdy,
tbdy.innerHTML+"<tr>"+
"<td>"+docType+"</td>"+
"<td>"+docno+"</td>"+
"<td>"+reqStatusArr.join("</br>")+"</td>"+
"<td>"+response+"</td></tr>"
);
});
});
}
dojo.byId("view:_id1:resTable").style.display="inline";
dojo.byId("idLoad").style.display="none";
RPC Service Code
<xe:jsonRpcService
id="jsonRpcService2"
serviceName="faUpdate">
<xe:this.methods>
<xe:remoteMethod name="updateAssignments">
<xe:this.arguments>
<xe:remoteMethodArg
name="dbPth"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="uniquekey"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="fieldList"
type="list">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="reassignee"
type="string">
</xe:remoteMethodArg>
</xe:this.arguments>
<xe:this.script><![CDATA[print ("starting update assignments from future assignments page");
var db:NotesDatabase = null;
var vw:NotesView = null;
var doc:NotesDocument = null;
try{
db=session.getDatabase("",dbPth);
if (null!= db){
print(db.getFileName());
vw = db.getView("DocUniqueKey");
if (null!=vw){
print ("got the view");
doc = vw.getDocumentByKey(uniquekey);
if (null!=doc)
{
//check if the document is not locked
if (doc.getItemValueString("DocLockUser")=="")
{
print ("Got the document");
for (i=0;i<fieldList.length;i++)
{
print (fieldList[i]);
doc.replaceItemValue(fieldList[i],reassignee);
}
doc.save(true);
return "SUCCESS";
}
else
{
return "FAIL - document locked by "+session.createName(doc.getItemValueString("DocLockUser")).getCommon();
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 0";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 1";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 2";
}
}
catch(e){
print ("Exception occured --> "+ e.toString());
return "FAIL - Contact IT Deptt - Code: 3";
}
finally{
if (null!=doc){
doc.recycle();
vw.recycle();
db.recycle();
}
}]]></xe:this.script>
</xe:remoteMethod>
</xe:this.methods>
</xe:jsonRpcService>
Thanks in advance
I have resolved this issue. First, CSJS variables were not reliably set in callback function so I made RPC return the HTML string I wanted. Second was my mistake in CSJS. I was trying to fetch tbody from table using
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
where as it returns an array so it should have been
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName**("tbody")[0]**;
also I moved tbody above while loop. I can post entire code if anyone is interested!!

Google Contacts API error

I'm using the following code to get google contacts name and phone number. Authorization page itself is not coming properly it shows error as "The page you requested is invalid". :( pls help me to solve this...
`
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("gdata", "1.x");
var contactsService;
function setupContactsService()
{
contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
}
function logMeIn() {
var scope = 'https://www.google.com/m8/feeds';
var token = google.accounts.user.login(scope);
}
function initFunc() {
setupContactsService();
logMeIn();
getMyContacts();
}
function checkLoggedIn(){
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.checkLogin(scope);
if(token != "")
return true;
else
return false;
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
//We load all results by default//
query.setMaxResults(10);
contactsService.getContactFeed(query, handleContactsFeed, ContactsServiceInitError);
}
//Gets the contacts feed passed as parameter//
var handleContactsFeed = function(result) {
//All contact entries//
entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var telNumbers = contactEntry.getPhoneNumbers();
var title = contactEntry.getTitle().getText();
}
}
</script>
<body>
<input type="submit" value="Login to Google" id="glogin" onclick="initFunc();">
</body>`
Thanks
It looks like you are trying to use the Google Contacts 1.X API. That's been deprecated. Look at the JavaScript examples for the Google 3.X API and see if that helps.
You can try this example
var config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json", function(response) {
console.log(response);
//console.log(response.data.feed.entry);
});
}
Don't forget to add <script src="https://apis.google.com/js/client.js"></script> into your html file. Good Luck!

Categories

Resources