Cordova OneSignal Plugin won't getIds properly - javascript

I got a small problem with the onesignal plugin for cordova.
When I'm running the app for the first time on wifi it won't get user's ids if I switch on mobile data it works just fine, after this works on wifi too.
This is the error i get on onesignal debugger:
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>My App</title>
</head>
<body>
Test
</body>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</html>
Index.js
var app = {
initialize: function()
{
this.bindEvents();
},
dump: function (obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
},
bindEvents: function()
{
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function()
{
app.receivedEvent('deviceready');
},
receivedEvent: function(id)
{
alert('init');
window.plugins.OneSignal
.startInit('onesignalid', 'googleproject')
.inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.Notification)
.handleNotificationOpened(app.notificationOpenedCallback)
.endInit();
app.getIds();
},
getIds: function()
{
window.plugins.OneSignal.getIds(function(ids){
app.dump(ids);
$.post('http://example.com/app_register_notif', {uid:'4764',onesignalid: ids.userId,onesignaltoken: ids.pushToken});
});
}
};
app.initialize();

The SERVICE_NOT_AVAILABLE is returned from Google Play services when it can't connect to get a registration id needed for push notifications. Your wifi network might be blocking a connection to Google if your cell connection works fine.
See the following stack overflow answer for more details.
https://stackoverflow.com/a/18325226/1244574

Related

Check internet connectivity in mobile application using phonegap

On creating the mobile app in phonegap, I would like to show an alert message regarding internet connectivity as online / offline. But I do not get the alert message. I used
cordova-plugin-network-information
plugin with the code below on my js file
<script type="text/javascript">
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]); </script>
Can any one help me with the solution?
First Add the below Cordova Plugins:
cordova plugin add cordova-plugin-network-information
cordova plugin add cordova-plugin-dialogs
Add Below cript files:
jquery.mobile-1.4.0.css jquery-1.10.2.min.js cordova.js
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" name="viewport"
content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<link rel="stylesheet" href="css/jquery.mobile-1.4.0.css" />
<script src="cordova.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js">
</script>
<script>
$(document).ready(function () {
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
function onDeviceReady() {
console.log(" ready");
}
function onOnline() {
console.log("connected");
}
function onOffline() {
debugger;
console.log("lost connection");
navigator.notification.alert(
'Please Check your internet connection.', // message
null, // callback
'Sample', // title
'OK' // buttonName
);
}
});
</script>
</head>
<body>
<p style="top:100px;"> Sample</p>
</body>
</html>
Output:
For More Details Click Here..!
You have to make sure that document has loaded before adding the above code. Do something like this in your HTML:
<body onload="onLoad">
and in your script/JS file do something like this:
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
//call your internet connectivity code here...
}

How to redirect response received from an Ajax request to another html page

I have a mongoose database that has data containing a person's first and last name. I have an input field where the user inputs their first name, and then an ajax request that sends the request to the file nameController.js. The code in this file creates a JSON response that contains all the names from the database that include the first name that the user mentioned. I would like to redirect this response to another html page (not index.html) called responsepage.html, and then have the response show up as a list. Does anyone know how to do this?
Here is my index.html code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; style-src 'self' http://* https://* 'unsafe-inline'; script-src 'self' http://* https://* 'unsafe-inline' 'unsafe-eval'">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<script src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/6.1.0/jquery.min.js">
<script src="js/jquery-3.3.1.min.js"></script>
<title>Hello World</title>
</head>
<body>
Enter your first name: <input id="firstName" name="name" type="text">
<button id="fnamelistbtn" >Click to see names</button>
</body>
</html>
Here is my index.js code
window.addEventListener("load", startup);
function startup() {
document.getElementById("fnamelistbtn").addEventListener("click", test);
//document.getElementById("el2").addEventListener("input", myFunc);
}
function test(){
alert("tested");
var firstnameneterd=document.getElementById("firstName");
alert(firstnameneterd.value);
var final_url= 'http://localhost:3000/director/cordovanames?name='+firstnameneterd.value;
$.ajax({
type:'GET',
//url:'http://localhost:3000/director/cordovanames?name=Vedant',
url:final_url,
dataType: "json",
success: function(response) {
var jsonparse=JSON.parse(response);
alert(jsonparse.length);
for (i = 0; i < jsonparse.length; i++) {
alert(jsonparse[i].lastName + ', ' + jsonparse[i].firstName);
}
},
error: function(err) {
alert("not worked");
alert(err);
return err;
}
});
}
Here is my nameController.js code
var Name = require('../models/name');
var url = require('url');
exports.cordovanames_list = function(req, res, next) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var fName = query.name;
Name.find({'firstName': fName})
.sort([['firstName', 'ascending']])
.exec(function (err, list_names) {
if (err) { return next(err); }
res.json(JSON.stringify(list_names));
});
};
Here is my responsepage.html code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; style-src 'self' http://* https://* 'unsafe-inline'; script-src 'self' http://* https://* 'unsafe-inline' 'unsafe-eval'">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<script src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="js/jquery-3.3.1.min.js"></script>
<title>Responses</title>
</head>
<body>
<p id="responsepara"></p>
<script>
var responsepara = document.getElementById('responsepara');
function showresponse(response) {
var jsonparse = JSON.parse(response)
alert(jsonparse.length);
for (i = 0; i < jsonparse.length; i++) {
responsepara.textContent = jsonparse[i].lastName + ', ' + jsonparse[i].firstName;
}
}
</script>
</body>
</html>
There are two solutions to the problem that I can think of now. First will be to save the response in localStorage or sessionStorage and retrieve it on the next page, or pass the response to the next page as a GET query string.
Method 1
// index.js
...
success: function(response) {
var res = JSON.stringify(JSON.parse(response));
window.localStorage.setItem('response', res);
window.location = '/response_page.html';
},
...
// response_page.html
...
$(document).ready(function() {
var response = window.localStorage.getItem('response');
// Clear storage
window.localStorage.clear();
showresponse(response);
});
...
Method 2
// index.js
...
success: function(response) {
var res = JSON.stringify(JSON.parse(response));
window.location = '/response_page.html?response=' + encodeURIComponent(res);
},
...
// response_page.html
...
$(document).ready(function() {
var response = window.location.search.split('=')[1];
showresponse(response);
});
...
The caveat with method 2 is that you are limited to a maximum of 2,048 characters.

Cordova File Opener Failing to Find File

I'm trying to use cordova-plugin-file-opener2 to load a pdf in Cordova. I can't seem to get it to work in the browser or on Android.
Here is my app.js file:
(function () {
document.querySelector('#file-button').addEventListener('click', openFile);
function openFile(){
console.log('opening file');
console.log(cordova.file.applicationDirectory);
var fileName = 'www/assets/pdf/foo.pdf';
var pathToFile = cordova.file.applicationDirectory + fileName;
window.resolveLocalFileSystemURL(pathToFile, function (entry) {
cordova.plugins.fileOpener2.open(
entry.toInternalURL(),
'application/pdf', {
error: function (e) {
alert.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
alert.log('file opened successfully');
}
}
);
}, function (e) {
alert('File Not Found');
});
}
}());
And here's the html:
<!DOCTYPE html>
<html>
<head>
<script src="cordova.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<p><button id="file-button" class="help-btn">Help</button></p>
<div class='header'><h1>Directory</h1></div>
<div class='search-view'>
<input class='search-key' type="search" placeholder="Enter name"/>
<ul class='list employee-list'></ul>
</div>
<script src="lib/jquery.js"></script>
<script src="js/services/memory/EmployeeService.js"></script>
<script src="js/app.js"></script>
</body>
</html>
When the 'file-button' is clicked, it triggers the openFile function.
This shows me the following in the console:
adding proxy for Device cordova.js:1010:9
adding proxy for File cordova.js:1010:9
opening file app.js:6:9
"http://localhost:8000/" app.js:7:9
And the alert message says 'File not found'.
App.js is located in www --> js
foo.pdf is located in www --> assets --> pdf

Websocket not working in android app using phonegap

I am trying to establish a websocket connection between my signalR server and an android app, built using the phonegap CLI.
The javascript code runs on browsers on my PC but when I package it for android it fails to connect and gives the following error: Error during negotiation request
Here is the javascript code -
<!DOCTYPE html>
<html>
<head>
<title>My New Application</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no;" />
<script type="text/javascript" src="js/jquery-1.7.1.js" ></script>
<script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="js/jquery.signalR-2.0.3.js"></script>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src=http://WEB_ADDRESS.net/signalrPush/signalr/hubs"></script>
<script type="text/javascript">
$(function() {
alert('Phonegap device ready event...');
/*
var connection = $.hubConnection("http://WEB_ADDRESS.net/signalrPush/signalr", { useDefaultPath: false });
connection.error(function (error){
alert("SignalR error: " + error);
});
var pushhubProxy = connection.createHubProxy('pushhub');
pushhubProxy.on('sendmsg',function(message){ $('#ulServerMessages').append('<li>' + message + '</li>'); alert(message);});
connection.start({ transport: ['webSockets', 'longPolling'] }).done(function(){ alert('Now connected, connection ID=' + connection.id);})
.fail(function(){ alert('Could not connect'); });
*/
$.connection.hub.url = "http://WEB_ADDRESS.net/signalrPush/signalr";
var mypushHub = $.connection.pushhub;
if(typeof(mypushHub)=="object")
{
alert(typeof(mypushHub));
mypushHub.client.sendmsg = function (message) {
$('#ulServerMessages').append('<li>' + message + '</li>');
alert(message);
}
$.connection.hub.start({jsonp: true}).done(function () {
mypushHub.server.broadcastmsg();
}).fail(function (error) { alert(error); });
}
else
{
alert(typeof(mypushHub));
alert("Connection Prob");
}
});
</script>
</head>
<body>
<div data-role="header">
<h1>Get Server Data</h1>
</div>
<div id="pusheddata" style="width:300px; height:400px; overflow: auto;">
<ul id="ulServerMessages"></ul>
</div>
</body>
</html>
The asp.net code is hosted on azure.
I also tried to connect without the generated proxy(commented code) which again worked on chrome but not on the android emulator(4.4).
Could someone tell me what I am doing wrong?
Thanks
I am having the same problem as you.
Websocket is a feature within html5 and is not supported by all browsers
Chrome browser supports websockets but android 4.4 (jelly beans) In-browser doesn't.
This is why Android developed kitkat (which supports the websocket).
If you want to use websocket within android 4.2,4.4 (jelly beans), you have to use websocket cordova plugin like the one here
there are alot of others and I am just like you trying to find an answer

Simple way of displaying images from parse.com database using javascript

I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});

Categories

Resources