how to read device token (parse.com) with phonegap/javascript iOS - javascript

I'm developing an app for iOS with Phonegap and I'm using parse.com for push notification with iOS SDK included with Xcode. In my app users can login and I need to know the device token of the users to send to them single push notification, I know how to send the device token with the user/password during log in but I don't know how to read it, I don't know if there is any way directly with Phonegap or if I need to read it with C and then pass to Javascript with a variable.
EDIT: I'm trying to use Malloc's solution, and i have this problem. i installed plugin via CLI but i don't understand how to use it. I create a sample page
<html>
<head>
</head>
<body>
<script type="text/javascript> parsePlugin.getInstallationId(function(id) { document.write(id); }, function(e) { alert('error'); });
</script>
</body>
</html>
but of course i obtain a white page because this code don't print anything.
What i need to do if i want to assign installationid to a javascript variable?
thanks
UPDATE 2
Now I have this code in my sample page
<html>
<head>
</head>
<body>
<script type="text/javascript">
var appId = p3Z10Nj2GdmfuxCX1a9liu5VlPadbvgW********;
var clientKey = lFRl93OEDM0bFTVOKaA1iIXV4vuWS3S9********;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
</script>
</body>
</html>
UPDATE 3
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(window).load(function() {
var appId = p3Z10Nj2gm8siK;
var clientKey = lFRl93OEDM0bFTVOKaA1iIXV4vu;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
}
</script>
</body>
</html>

What you need is the device related installation id. You may need to use a plugin for this.
The plugin I have used, and which worked as expected, can be found here.
After installing it with the CLI, you just call the parsePlugin.getInstallationId function which will return the installation id for your device.
Keep in mind that you will get ONE installation id per device but that doesn't mean that you have always only one. Since you may run the app on more than a device, each one has his installation id.
Update:
The plugin should be initialized before calling getInstallationId:
$(window).load(function() {
var appId = YOUR_APP_ID;
var clientKey = YOUR_KEY_CLIENT;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
}

You should be using a plugin as others pointed out, here is another plugin that does the same job.
https://github.com/ccsoft/cordova-parse
PS: I am the author of the plugin.

Related

"ScriptError: Authorisation is required to perform that action." when running google.script.run from Library

Regards,
I have found several questions regarding this error :
"ScriptError: Authorisation is required to perform that action." but I can't find one that is about my issue.
What I am trying to do is call a function .gs file from .html file using google.script.run where both of the file is in Library. Referring to this answer, this answer and this bug report, I have created the "wrapper function" in the script that is using the library, but still failed to finish the execution.
Here's what I did :
.html in Library :
<html>
<head>
<script>
function onFailure(error) {
console.log("ERROR: " + error);
}
function myfunc() {
console.log("HERE");
google.script.run.withFailureHandler(onFailure).callLibraryFunction('LibraryName.test', ['test123']);
}
</script>
</head>
<body>
<button onclick="myfunc()">CLICK</button>
</body>
</html>
.gs in Library
function test(x){
Logger.log(x);
}
.gs in script that is using the Library:
function callLibraryFunction(func, args) {
var arr = func.split(".");
var libName = arr[0];
var libFunc = arr[1];
args = args || [];
return this[libName][libFunc].apply(this, args);
}
The console logs HERE but then it logs ERROR: ScriptError: Authorisation is required to perform that action. instead of the expected output, test123.
NOTE: The HTML is for custom modeless dialog box in Sheets and not for Web App.
I really hope someone can help me in this. Thank you in advance.
You need to grant access of the library "LibraryName" as an authorized app in your Gmail account the same way how you grant access to the calling script. I guess you have called the method HtmlService.createHtmlOutputFromFile(...) in your library. This requires more authorization. You need to grant this. What you can do is create a temporary function in the library that has HtmlService.createHtmlOutputFromFile(..). Run it from the script editor and the authorization requirement window appears. Proceed in granting access...

Why do I get an error with an example from PhantomJS documentation?

I took an example from http://phantomjs.org/page-automation.html because I need to press a button on JS site before scraping.
var page = require('webpage').create();
page.open('http://www.sample.com', function() {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
$("button").click();
});
phantom.exit()
});
});
But when I run this code, I get this error:
work7.rb:5: `$(' is not allowed as a global variable name
work7.rb:5: syntax error, unexpected end-of-input $("button").click();
Is PhantomJS required properly?
var page = require('webpage').create();
page.open('http://example.com', function(status) {
});
It doesn't work!
/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- webpage (LoadError)
from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in
require'
from work7.rb:3:in '
What am I doing wrong?
This question is really confusing...
Your code is written in JavaScript, not in Ruby! To execute JavaScript code, you need a JavaScript runtime environment. The most popular ones nowadays are (graphical and headless) web browsers, Node.js and Electron.
PhantomJS is a web browser. It does not have a graphical interface, but this is a real, full-fledged, web browser that you can automate with scripts. To run a regular PhantomJS script written in JavaScript, you have to use the phantomjs command that should be available in your PATH if you installed phantomjs-prebuilt globally on your system with npm.
To help you getting started, you will find below a working example (without jQuery) where PhantomJS clicks a button of the webpage which triggers a JS alert containing the following message: "It works!". This message is captured by the onAlert event handler and printed to the console.
HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PhantomJS</title>
</head>
<body>
<button>OK</button>
<script>
(function () {
var button = document.querySelector('button');
button.addEventListener('click', function () {
alert('It works!');
}, false);
})();
</script>
</body>
</html>
JavaScript (script.js)
var page = require('webpage').create();
page.onAlert = function (msg) {
console.log(msg);
};
page.open('index.html', function () {
page.evaluate(function () {
document.querySelector('button').click();
});
phantom.exit()
});
Command
phantomjs script.js

How to implement in-app-purchase using Cordova plugin?

Please tell me the way to implement in-app-purchase using Cordova plugin.
I'm developing Android application using Cordova.
There are some in-app-purchase plugins but I decide to use Cordova Purchase Plugin.
I did some setups along README.md of In-App Purchase for PhoneGap / Cordova iOS and Android.
As a result, I could call the Plugin using Demo of the Purchase Plugin for Cordova with my little modification. (See the following, it is a portion of code.)
app.initStore = function() {
if (!window.store) {
log('Store not available');
return;
}
// Enable maximum logging level
store.verbosity = store.DEBUG;
// Enable remote receipt validation
// store.validator = "https://api.fovea.cc:1982/check-purchase";
// Inform the store of your products
log('registerProducts');
store.register({
id: 'myProductA',
alias: 'myProductA',
type: store.CONSUMABLE
});
// When any product gets updated, refresh the HTML.
store.when("product").updated(function (p) {
console.info("app.renderIAP is called");
app.renderIAP(p);
});
// Log all errors
store.error(function(error) {
log('ERROR ' + error.code + ': ' + error.message);
});
// When purchase of an extra life is approved,
// deliver it... by displaying logs in the console.
store.when("myProductA").approved(function (order) {
log("You got a ProductA");
order.finish();
});
// When the store is ready (i.e. all products are loaded and in their "final"
// state), we hide the "loading" indicator.
//
// Note that the "ready" function will be called immediately if the store
// is already ready.
store.ready(function() {
var el = document.getElementById("loading-indicator");
console.info(el + "ready is called")
if (el)
el.style.display = 'none';
});
// When store is ready, activate the "refresh" button;
store.ready(function() {
var el = document.getElementById('refresh-button');
console.info(el + "ready is called and refresh-button show?");
if (el) {
el.style.display = 'block';
el.onclick = function(ev) {
store.refresh();
};
}
});
// Refresh the store.
//
// This will contact the server to check all registered products
// validity and ownership status.
//
// It's fine to do this only at application startup, as it could be
// pretty expensive.
log('refresh');
store.refresh();
};
It did not show 'Store not available' that is shown when plugin is not available, show 'registerProducts', and 'refresh.'
(*Of course I added 'myProductA' to in-app Products on Google Play Developer Console.)
But I noticed that the below function is not called.
store.when("product").updated(function (p)
And also I couldn't understand what the parameter should fill in it, so I commented out the below.
(*I did remove the comment out, but it still not working.)
store.validator = "https://api.fovea.cc:1982/check-purchase";
I guess those things make something wrong.
I'm not sure what is stack on me, so my question is not clearly.
I want some clues to solve it... or I shouldn't implement in-app-purchase using Cordova plugin?
Please give me your hand.
(I'm not fluent in English, so I'm sorry for any confusion.)
You can try this plugin as an alternative: https://github.com/AlexDisler/cordova-plugin-inapppurchase
Here's an example of loading products and making a purchase:
inAppPurchase
.buy('com.yourapp.consumable_prod1')
.then(function (data) {
// ...then mark it as consumed:
return inAppPurchase.consume(data.productType, data.receipt, data.signature);
})
.then(function () {
console.log('product was successfully consumed!');
})
.catch(function (err) {
console.log(err);
});
It supports both Android and iOS.
Step for Integrate In-App billing in Phone-gap app.
1>> clone this project in your pc from this link In-App billing Library
2>> using CMD go to your root directory of your phonegap application
3>> then run this command cordova plugin add /path/to/your/cloned project --variable BILLING_KEY="QWINMERR..........RIGR"
Notes : for BILLING_KEY go to Developer console then open your application and go to Service& APIs for more info Please refer attached screenshots

Trigger local notification for iOS - Cordova/Phonegap

I am using this plugin and trying to trigger local notification for my Cordova iOS app with Local notifications plugin.
I dd following steps:
Installed plugin: cordova plugin add de.appplant.cordova.plugin.local-notification#0.7.7
Updated config.xml: gap:plugin name="de.appplant.cordova.plugin.local-notification"
Added the following JavaScript in head tag for
index.html
plugin.notification.local.promptForPermission(function (granted) {
alert("promptForPermission: "+granted);
});
plugin.notification.local.hasPermission(function (granted) {
alert("hasPermission: "+granted);
});
Have a button in index.html to create a local notification after 5 secs.
Code for that looks like this:
function setLocalNotification()
{
alert("from setLocalNotification");
var t = new Date();
t.setSeconds(t.getSeconds() + 3);
window.plugin.notification.local.add({
title: 'Scheduled with delay',
message: 'Test Message ',
date: t
});
alert("alert set");
};
I do see a prompt for user's permission and the alert from hasPermission method shows the value as true. But I am still not able to get the actual local notification I am trying to set by clicking a button. I have already updated the APPLocalNotification.m file for the this issue by copying this fix.
I don't see any more errors in the console log but I am still not able to trigger a local notification.
You should check if the device is ready ( document.addEventListener('deviceready', function () {
) and also check if the plugin is correctly added $ cordova plugin ls.
Make sure you have "< script type="text/javascript" src="cordova.js">
" in your html .
Good luck!

API Key Error in Facebook Connect (javascript sdk)

I am trying to implement Facebook Connect on a website. I am trying to work with Javascript SDK of Facebok. I am new to it and unfortunately most of links provided in Facebook WIKI are out of date... Returning 404 not found. Anyway I added this code before the ending </body>:
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
<div id="fb-root"></div>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"> </script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '12344', // my real app id is here
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : false // parse XFBML
});
FB.login(function(response) {
if (response.session) {
if (response.perms) {
alert('user is logged in and granted some permissions');
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
alert('user is logged in, but did not grant any permissions');
// user is logged in, but did not grant any permissions
}
} else {
alert('user is not logged in');
// user is not logged in
}
}, {perms:'email'});
</script>
And I have a login button at some other place (much before the above scripts) in the same page rendered with:
<fb:login-button v="2">Connect with Facebook</fb:login-button>
This button renders as a normal fb connect button and clicking it opens a new popup window as it normally should. Problem is that it shows 'invalid api key specified' error. On inspecting address bar of popup, I see that api_key=undefined is passed to it :(
Any idea about this? I am trying to fix this for last 5 hours now... Please help me found out why correct API key is not being passed to popup window.
Thanks in advance.
I'm doing the same thing, and i found an example that is very simple to implement and understand (here thay use jQuery, but you can do the same without libraries):
<body>
<div>
<button id="login">Login</button>
<button id="disconnect">Disconnect</button>
</div>
<div id="user-info" style="display: none;"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with the API key
FB.init({ appId : '12344' });
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});
$('#disconnect').bind('click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
if (!response.session) {
clearDisplay();
return;
}
// if we have a session, query for the user's profile picture and name
FB.api(
{
method: 'fql.query',
query: 'SELECT name, pic FROM profile WHERE id=' + FB.getSession().uid
},
function(response) {
var user = response[0];
$('#user-info').html('<img src="' + user.pic + '">' + user.name).show('fast');
}
);
}
</script>
</body>
Look here for the entire code, and here you can find other resource.
I had set my facebook connect address to have www and I was accessing my test site with non www, when I switched to the www version fb connect worked fine.
You need to set the canvas post-authorize url, and make sure that the base canvas url is a prefix of the post-authorize url.

Categories

Resources