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);
});
}
Related
I'm trying to get my first dapp working; I know I'm close, but keep running into a problem with web3.
I am working on Windows 10, running a testrpc node via PowerShell. I used truffle to set up my folders & sample files, then compile and migrate.
I don't think I changed anything from the app.js file built by truffle... here is that code:
var accounts;
var account;
function setStatus(message) {
var status = document.getElementById("status");
status.innerHTML = message;
};
function refreshBalance() {
var meta = MetaCoin.deployed();
meta.getBalance.call(account, {from: account}).then(function(value) {
var balance_element = document.getElementById("balance");
balance_element.innerHTML = value.valueOf();
}).catch(function(e) {
console.log(e);
setStatus("Error getting balance; see log.");
});
};
function calcPremium() {
var premium = parseInt(document.getElementById("benefit").value)/10000;
document.getElementById("monthlyPremium").innerHTML = " Monthly Premium: $"+premium.toFixed(2);
};
function sendCoin() {
var meta = MetaCoin.deployed();
var amount = parseInt(document.getElementById("monthlyPremium").value);
var receiver = document.getElementById("receiver").value;
setStatus("Initiating transaction... (please wait)");
meta.sendCoin(receiver, amount, {from: account}).then(function() {
setStatus("Transaction complete!");
refreshBalance();
}).catch(function(e) {
console.log(e);
setStatus("Error sending coin; see log.");
});
};
window.onload = function() {
web3.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}
I'm able to open the html file in a Chrome browser, with the MetaMask plugin enabled. However, it seems I'm unable to interact with the contracts in any way, due to the web3 error issue. The exact message is this post's subject line.
Thanks in advance for any help or guidance!
Could you please try it and see . I think the onload is giving the issue.
$(window).load function() {
web3.eth.getAccounts(function(err,accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}
I am following this article on Social Logins with AngularJS and ASP.Net WebAPI (which is quite good):
ASP.NET Web API 2 external logins with Facebook and Google in AngularJS app
Pretty much, the code works fine when you are running the social login through a desktop browser (i.e. Chrome, FF, IE, Edge). The social login opens in a new window (not tab) and you are able to use either your Google or Facebook account and once your are logged in through any of them, you are redirected to the callback page (authComplete.html), and the callback page has a JS file defined (authComplete.js) that would close the window and execute a command on the parent window.
the angularJS controller which calls the external login url and opens a popup window (not tab) on desktop browsers:
loginController.js
'use strict';
app.controller('loginController', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) {
$scope.loginData = {
userName: "",
password: "",
useRefreshTokens: false
};
$scope.message = "";
$scope.login = function () {
authService.login($scope.loginData).then(function (response) {
$location.path('/orders');
},
function (err) {
$scope.message = err.error_description;
});
};
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.$windowScope = $scope;
var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
};
$scope.authCompletedCB = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authService.logOut();
authService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authService.obtainAccessToken(externalData).then(function (response) {
$location.path('/orders');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
}]);
authComplete.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="scripts/authComplete.js"></script>
</body>
</html>
authComplete.js
window.common = (function () {
var common = {};
common.getFragment = function getFragment() {
if (window.location.hash.indexOf("#") === 0) {
return parseQueryString(window.location.hash.substr(1));
} else {
return {};
}
};
function parseQueryString(queryString) {
var data = {},
pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
if (queryString === null) {
return data;
}
pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
escapedKey = pair;
escapedValue = null;
} else {
escapedKey = pair.substr(0, separatorIndex);
escapedValue = pair.substr(separatorIndex + 1);
}
key = decodeURIComponent(escapedKey);
value = decodeURIComponent(escapedValue);
data[key] = value;
}
return data;
}
return common;
})();
var fragment = common.getFragment();
window.location.hash = fragment.state || '';
window.opener.$windowScope.authCompletedCB(fragment);
window.close();
The issue I am having is that when I run the application on a mobile device (Safari, Chrome for Mobile), the social login window opens in a new tab and the JS function which was intended to pass back the fragment to the main application window does not execute nad the new tab does not close.
You can actually try this behavior on both a desktop and mobile browser through the application:
http://ngauthenticationapi.azurewebsites.net/
What I have tried so far in this context is in the login controller, I modified the function so that the external login url opens in the same window:
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.location = externalProviderUrl;
};
And modified the authComplete.js common.getFragment function to return to the login page, by appending the access token provided by the social login as query string:
common.getFragment = function getFragment() {
if (window.location.hash.indexOf("#") === 0) {
var hash = window.location.hash.substr(1);
var redirectUrl = location.protocol + '//' + location.host + '/#/login?ext=' + hash;
window.location = redirectUrl;
} else {
return {};
}
};
And in the login controller, I added a function to parse the querystring and try to call the $scope.authCompletedCB(fragment) function like:
var vm = this;
var fragment = null;
vm.testFn = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authenticationService.logOut();
authenticationService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authenticationService.obtainAccessToken(externalData).then(function (response) {
$location.path('/home');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
init();
function parseQueryString(queryString) {
var data = {},
pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
if (queryString === null) {
return data;
}
pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
escapedKey = pair;
escapedValue = null;
} else {
escapedKey = pair.substr(0, separatorIndex);
escapedValue = pair.substr(separatorIndex + 1);
}
key = decodeURIComponent(escapedKey);
value = decodeURIComponent(escapedValue);
data[key] = value;
}
return data;
}
function init() {
var idx = window.location.hash.indexOf("ext=");
if (window.location.hash.indexOf("#") === 0) {
fragment = parseQueryString(window.location.hash.substr(idx));
vm.testFn(fragment);
}
}
But obviously this is giving me an error related to angular (which I have no clue at the moment):
https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest
So, pretty much it is a dead end for me at this stage.
Any ideas or input would be highly appreciated.
Gracias!
Update: I managed to resolve the Angular error about the rootscope being thrown, but sadly, resolving that does not fix the main issue. If I tried to open the social login on the same browser tab where my application is, Google can login and return to the application and pass the tokens required. It is a different story for Facebook, where in the Developer's tools console, there is a warning that seems to stop Facebook from displaying the login page.
Pretty much, the original method with which a new window (or tab) is opened is the way forward but fixing the same for mobile browser seems to be getting more challenging.
On desktop, when the auth window pops up (not tab) it has the opener property set to the window which opened this pop up window, on mobile, as you said, its not a pop up window but a new tab. when a new tab is opened in the browser, the opener property is null so actually you have an exception here:
window.opener.$windowScope.authCompletedCB
because you can't refer the $windowScope property of the null value (window.opener) so every line of code after this one wont be executed - thats why the window isn't closed on mobile.
A Solution
In your authComplete.js file, instead of trying to call
window.opener.$windowScope.authCompletedCB and pass the fragment of the user, save the fragment in the localStorage or in a cookie (after all the page at authComplete.html is in the same origin as your application) using JSON.stringify() and just close the window using window.close().
In the loginController.js, make an $interval for something like 100ms to check for a value in the localStorage or in a cookie (don't forget to clear the interval when the $scope is $destroy), if afragment exist you can parse its value using JSON.parse from the storage, remove it from the storage and call $scope.authCompletedCB with the parsed value.
UPDATE - Added code samples
authComplete.js
...
var fragment = common.getFragment();
// window.location.hash = fragment.state || '';
// window.opener.$windowScope.authCompletedCB(fragment);
localStorage.setItem("auth_fragment", JSON.stringify(fragment))
window.close();
loginController.js
app.controller('loginController', ['$scope', '$interval', '$location', 'authService', 'ngAuthSettings',
function ($scope, $interval, $location, authService, ngAuthSettings) {
...
// check for fragment every 100ms
var _interval = $interval(_checkForFragment, 100);
function _checkForFragment() {
var fragment = localStorage.getItem("auth_fragment");
if(fragment && (fragment = JSON.parse(fragment))) {
// clear the fragment from the storage
localStorage.removeItem("auth_fragment");
// continue as usual
$scope.authCompletedCB(fragment);
// stop looking for fragmet
_clearInterval();
}
}
function _clearInterval() {
$interval.cancel(_interval);
}
$scope.$on("$destroy", function() {
// clear the interval when $scope is destroyed
_clearInterval();
});
}]);
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.
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!
I am stuck with Social login (Facebook, Google and twitter) through Phonegap.
I have googled and found so many solutions, but they don't work on either platform (i.e: android or iOS).
Does any one have implemented social login in his/her app using phonegap?
If any one could provide me the running code, that would be appreciated.
Thanks,
Sabir
I know it's probably late to answer your particular question but I have had the same issue - all of the current (September 2016) scripts, snippets and libraries for social login in PhoneGap/Cordova that I have tried did not work so I made some simple functions from scratch which may still be useful to people ending up here. You can use them to log the user in with LinkedIn, Facebook and Google(+). I have also made some simple functions that retrieve some basic user information from the access token that is returned by logging the user in with the given network. You can examine the functions but they usually save the token or/and the user data to localStorage for later usage. They have been tested in September 2016 and work perfectly. I hope that this would help other people who also land on failing snippets around the web.
You can just insert the code and use the functions whenever you want. It requires jQuery and PhoneGap's InAppBrowser (besides having made apps/clients in the social media in order to fill the app id and app secret).
As a side note, it is not the best move to store the client secret directly in the PhoneGap application as the source can be viewed by malevolent people.
The code can be refactored at many places, so feel free to do that, but it does the trick. You may also have to handle cases where the user cancels the login process.
var facebookLogin = function(appId, appSecret, successCb,errCb) {
/*$.get("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" +appSecret + "&grant_type=client_credentials", function(res) {
if (res.indexOf("access_token=") !== -1) {
successCb(res.replace("access_token=", "").trim());
}
else {
errCb(res);
}
})
*/
var ref = window.open("https://www.facebook.com/dialog/oauth?display=popup&response_type=token&client_id="+appId+"&redirect_uri="+"http://anyurlhere.com", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("#access_token") !== -1) {
localStorage.fbToken = evt.url.split("#access_token=")[1];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.fbToken);
})
}
}
})
}
var linkedinLogin = function(appId,appSecret,successCb,errCb) {
var ref = window.open("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id="+appId+"&redirect_uri="+(encodeURI("http://anyurlhere.com"))+"&state=987654321&scope=r_basicprofile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("code=") !== -1) {
var code = evt.url.split("code=")[1];
code = code.split("&")[0];
//TODO: get actual token to access user profile
$.post("https://www.linkedin.com/oauth/v2/accessToken", {"grant_type": "authorization_code", "code": code, "redirect_uri":encodeURI("http://anyurlhere.com"), "client_id":appId,"client_secret":appSecret}, function(data) {
for (key in data) {
if (key == 'access_token') {
localStorage.linkedinToken = data[key];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.linkedinToken);
})
}
}
})
}
}
})
}
var googleLogin = function(appId, appSecret, successCb, errCb) {
var ref = window.open("https://accounts.google.com/o/oauth2/v2/auth?response_type=token&client_id=" + appId + "&redirect_uri="+encodeURI("http://anyurlhere.com")+"&scope="+encodeURIComponent("email profile")+"&state=profile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("access_token=") !== -1) {
var accessToken = evt.url.split("access_token=")[1];
accessToken = accessToken.split("&")[0];
localStorage.gToken = accessToken;
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.gToken);
})
}
}
})
}
var getGoogleInfo = function(successCb, errCb) {
//get basic user profile
$.get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + localStorage.gToken, function(userInfo) {
successCb(userInfo);
})
}
var getFacebookInfo = function(successCb, errCb) {
//get basic user profile-name
$.get("https://graph.facebook.com/me?fields=email,name,picture&access_token=" + localStorage.fbToken, function(userInfo) {
var myInfo = {};
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.email) {
myInfo.email = userinfo.email;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture.data.url;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
// localStorage.myInfo = myInfo;
})
}
//get basic data for linked in
var getLinkedinInfo = function(successCb, errCb) {
$.ajax({
url: "https://api.linkedin.com/v1/people/~?format=json",
headers: {
"Authorization": "Bearer " + localStorage.linkedinToken
},
success: function(userInfo) {
var myInfo = {};
if (userInfo.firstName && userInfo.lastName) {
myInfo.name = userInfo.firstName + " " + userInfo.lastName;
}
if (userInfo.headline) {
myInfo.linkedinHeadline = userInfo.headline;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
},
fail: function(err) {
alert(err);
for (key in err) {
alert(key);
alert(err[key]);
}
}
})
}
//example of logging in the user with Google + and getting his/her data
googleLogin("93-54932-423-fkfew.apps.googleusercontent.com", "", function(accessToken) {
getGoogleInfo(function(userInfo) {
var myInfo = {};
alert(userInfo.name);
if (userInfo.email) {
myInfo.email = userInfo.email;
}
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.given_name) {
myInfo.firstName = userInfo.given_name;
}
if (userInfo.familyName) {
myInfo.familyName = userInfo.family_name;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture;
}