Cordova File Opener Failing to Find File - javascript

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

Related

Uncaught TypeError: Cannot read property 'isAvailable' of undefined;

I am trying to get the tutorial from Cordova GooglePlus to work. I havent spent about 16 hours on it over the past 3 days, combing stackoverflow, google, and github and I've come far but I keep getting an uncaught type error. It seems that I am not referencing the functions in GooglePlus.js correctly. Any tips would be appreciated. Here's the apk I created, which gives the same errors App.apk
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="format-detection" content="telephone=no"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height"/>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<meta name="msapplication-tap-highlight" content="no"/>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="plugins/cordova-plugin-googleplus/www/GooglePlus.js"></script>
<title>Hello World</title>
<script type="text/javascript">
app.initialize();
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function isAvailable() {
window.plugins.googleplus.isAvailable(function(avail) {alert(avail)});
}
function login() {
window.plugins.googleplus.login(
{},
function (obj) {
document.querySelector("#image").src = obj.imageUrl;
document.querySelector("#image").style.visibility = 'visible';
document.querySelector("#feedback").innerHTML = "Hi, " + obj.displayName + ", " + obj.email;
},
function (msg) {
document.querySelector("#feedback").innerHTML = "error: " + msg;
}
);
}
function trySilentLogin() {
window.plugins.googleplus.trySilentLogin(
{},
function (obj) {
document.querySelector("#image").src = obj.imageUrl;
document.querySelector("#image").style.visibility = 'visible';
document.querySelector("#feedback").innerHTML = "Silent hi, " + obj.displayName + ", " + obj.email;
},
function (msg) {
document.querySelector("#feedback").innerHTML = "error: " + msg;
}
);
}
function logout() {
window.plugins.googleplus.logout(
function (msg) {
document.querySelector("#image").style.visibility = 'hidden';
document.querySelector("#feedback").innerHTML = msg;
},
function (msg) {
document.querySelector("#feedback").innerHTML = msg;
}
);
}
function disconnect() {
window.plugins.googleplus.disconnect(
function (msg) {
document.querySelector("#image").style.visibility = 'hidden';
document.querySelector("#feedback").innerHTML = msg;
},
function (msg) {
document.querySelector("#feedback").innerHTML = msg;
}
);
}
window.onerror = function(what, line, file) {
alert(what + '; ' + line + '; ' + file);
};
function handleOpenURL (url) {
document.querySelector("#feedback").innerHTML = "App was opened by URL: " + url;
}
</script>
</head>
<body onload="onLoad">
<div class="app">
<img id="image" style="position:absolute; top:10px; left:10px" src="" />
<h1>Google+</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
<p id="feedback">not logged in</p>
<button onclick="isAvailable()">Available?</button>
<br/><br/>
<button onclick="login()">Login with Google+</button>
<br/><br/>
<button onclick="trySilentLogin()">Try silent login with Google+</button>
<br/><br/>
<button onclick="logout()">Logout</button>
<button onclick="disconnect()">Disconnect</button>
<br/><br/>
<button onclick="window.plugins.googleplus.getSigningCertificateFingerprint(function(res){alert(res)}, function(res){alert(res)})">get cert fingerprint (Android)</button>
</div>
</div>
</body>
</html>
At a glance, it looks like you may be missing an identifier in the chain.
Your isAvailable() function:
window.plugins.isAvailable(...);
vs repo's:
window.plugins.googleplus.isAvailable(...);
The scripts in your code have relative paths so I can't test it, but googleplus is present elsewhere in your code, specifically as a property of window.plugins, so I'm guessing that's the culplrit.

Cordova OneSignal Plugin won't getIds properly

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

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

How to download external file using phonegap?

I am trying to download an apk file on a button click using phonegap. Why does this code not work? Nothing happens when I click Download. Could someone point me in the right direction? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function foo()
{
var fileTransfer = new FileTransfer();
fileTransfer.download(
"http://samplewebsite.com/example.apk",
"file:///sdcard/example.apk",
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
</script>
</head>
<body>
<button onclick="foo()">Download</button>
</body>
</html>
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var filePath= "/sdcard/directory/file.extension";
fileTransfer.download(uri,filePath,
function(entry) {
//success
},
function(error) {
//failed
}
);
This worked for me
Your code works fine.
This seems stupid but have you tried to use alert() instead of console.log() in the callbacks?
If you are sure the callback code is not invoked try to run just the app created by the phonegap' create script and check that the device is ready before doing other tests.
just my 2c

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