framework.realtime.co and phonegap for Android - html

I'm making a web with framework.realtime.co. It works perfect on web, but when I compile mi web to an app with phonegap, the app works perfect but the connection realtime never works.
On the web version I have msj "Connected" but on the compiled version with phonegap, it just says nothing.
here is the html
<div id="status">
Loading...
</div>
Here is the code js
loadOrtcFactory(IbtRealTimeSJType, function (factory, error) {
if (error != null) {
//////console.log("Factory error: " + error.message);
} else {
client = factory.createClient();
client.setClusterUrl('https://ortc-developers-useast1.realtime.co/server/ssl/2.1');
client.onConnected = function(c) {
document.getElementById('status').innerHTML = "connected";
// send("New hello world");
c.subscribe('channelAlerta', true, elem_received);
}
client.onDisconnected = function() {
document.getElementById('status').innerHTML = "disconnected";
}
client.onReconnecting = function() {
document.getElementById('status').innerHTML = "reconnected ...";
}
client.connect(appkey, token);
}
});

You need to use a websocket PhoneGap plugin. Check the example at
https://github.com/realtime-framework/Messaging/tree/master/PhoneGap

Related

Web NFC on Chrome Android

I am trying to explore on web NFC and found a simple sample (https://googlechrome.github.io/samples/web-nfc/). So, I copy the sample code to test it on local:
<html><head>
<title>Web NFC Sample</title>
<script>
// Add a global error event listener early on in the page load, to help ensure that browsers
// which don't support specific functionality still end up displaying a meaningful message.
window.addEventListener('error', function(error) {
if (ChromeSamples && ChromeSamples.setStatus) {
console.error(error);
ChromeSamples.setStatus(error.message + ' (Your browser may not support this feature.)');
error.preventDefault();
}
});
</script>
<link rel="stylesheet" href="Web%20NFC%20Sample_files/main.css">
</head>
<body>
<button id="scanButton">Scan</button>
<button id="writeButton">Write</button>
<script>
var ChromeSamples = {
log: function() {
var line = Array.prototype.slice.call(arguments).map(function(argument) {
return typeof argument === 'string' ? argument : JSON.stringify(argument);
}).join(' ');
document.querySelector('#log').textContent += line + '\n';
},
clearLog: function() {
document.querySelector('#log').textContent = '';
},
setStatus: function(status) {
document.querySelector('#status').textContent = status;
},
setContent: function(newContent) {
var content = document.querySelector('#content');
while(content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
content.appendChild(newContent);
}
};
</script>
<h3>Live Output</h3>
<div id="output" class="output">
<div id="content"></div>
<div id="status">Web NFC is not available.
Please make sure the "Experimental Web Platform features" flag is enabled on Android.</div>
<pre id="log"></pre>
</div>
<script>
if (/Chrome\/(\d+\.\d+.\d+.\d+)/.test(navigator.userAgent)){
// Let's log a warning if the sample is not supposed to execute on this
// version of Chrome.
if (89 > parseInt(RegExp.$1)) {
ChromeSamples.setStatus('Warning! Keep in mind this sample has been tested with Chrome ' + 89 + '.');
}
}
</script>
<script>
log = ChromeSamples.log;
if (!("NDEFReader" in window))
ChromeSamples.setStatus(
"Web NFC is not available.\n" +
'Please make sure the "Experimental Web Platform features" flag is enabled on Android.'
);
</script>
<script>scanButton.addEventListener("click", async () => {
log("User clicked scan button");
try {
const ndef = new NDEFReader();
await ndef.scan();
log("> Scan started");
ndef.addEventListener("readingerror", () => {
log("Argh! Cannot read data from the NFC tag. Try another one?");
});
ndef.addEventListener("reading", ({ message, serialNumber }) => {
log(`> Serial Number: ${serialNumber}`);
log(`> Records: (${message.records.length})`);
});
} catch (error) {
log("Argh! " + error);
}
});
writeButton.addEventListener("click", async () => {
log("User clicked write button");
try {
const ndef = new NDEFReader();
await ndef.write("Hello world!");
log("> Message written");
} catch (error) {
log("Argh! " + error);
}
});
</script>
</body></html>
But when I run it, it shows Web NFC is not available. Please make sure the "Experimental Web Platform features" flag is enabled on Android. on the message. When I click on "scan" button, it shows Argh! ReferenceError: NDEFReader is not defined.
May I know why the sample code work well when it is on https://googlechrome.github.io but can't work when I have it on my local PC? Thank you.
As documented in https://web.dev/nfc/#security-and-permissions, Web NFC is only available in secure browsing contexts. It means you either have to serve your webpage over https:// or localhost such as http://127.0.0.1 or http://localhost.
If you have installed npm, you can use npx http-serve.
If you have installed Python 2, use python -m SimpleHTTPServer
If you have installed Python 3, use python -m http.server

Connecting to Openshift WebSocket issue

I'm trying to make my OpenShift Node.js app working, but the WS connection is not working. Client error is: connection refused.
Client side factory service:
var dataStream = $websocket(localStorageService.get('wsUrl'))
dataStream.onMessage(function(message) {
var call = JSON.parse(message.data)
if (fnMap[call.fn]) {
fnMap[call.fn](call.event, call.data)
}
})
dataStream.onError(function(err) {
console.log(err)
})
dataStream.onClose(function(event){
console.log('event: ' + JSON.stringify(event))
})
var fnMap = {
"broadcastResult": function(event, data) {
$rootScope.$broadcast(event, data)
}
}
var methods = {
callFn: function(paramJSON) {
dataStream.send(JSON.stringify(paramJSON));
}
}
return methods
I'm trying to connect on the following URL: ws://myapp-myname.rhcloud.com:8000
Could you please help?
Thank you in advance,
Csaba
First, you may want to make sure the websocket library, ws, is installed by declaring it in the dependencies section of your package.json and then doing another git push.
Otherwise, try the example provided in the openshift blog: https://blog.openshift.com/paas-websockets/
Specifically:
var websocket = new WebSocket("ws://myapp-myname.rhcloud.com:8000");
websocket.onopen = function(event) {
// The connection was opened
console.log(event)
};
websocket.onclose = function(event) {
// The connection was closed
console.log(event)
};
websocket.onmessage = function(event) {
// New message arrived
message = event.data
console.log(event)
};
websocket.onerror = function(event) {
// There was an error with your WebSocket
console.log(event)
};
The above at least might help point you toward a specific part of your code that's not working. Or, if the example isn't even working, it could be possibly something wrong with your cartridge, and you could try reaching out to RedHat's support.

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest'

I need to display hello world using servlet program in browser by Ajax call but on clicking button I am not to display it what could be reason of this error:
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/workspace/Poc_Ajax/WebContent/WEB-INF/HelloWorld'.
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "HelloWorld", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send();
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
</script>
</head>
<body>
<div>Getting Started with AJAX using JAVA: Hello World!</div>
<div id="hello"><button type="button" onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>
To run a servlet program you need to make an HTTP request to a web server that is configured to execute the servlet.
Your Ajax URL (as displayed in the error message) starts with file:// so you are trying to deal with a local file instead of a webserver.
Install a webserver (such as Tomcat). Load your HTML document from it. Make sure that "HelloWorld" is a relative URI from that HTML document to the servlet URL.

How to exit an application on Windows Phone 8 programmatically

I am creating an application in which when i press the cancel button the application should close.
for that I have used " navigator.app.exitApp()" statement as given a solution in stack overflow.
This solution is working in android but it is not working in windows phone 8.
Windows phone is throwing exception that "Unable to get property 'exitApp' of undefined or null reference"
I have written following code for this.
cancelLogin: function () {
var result = DevExpress.ui.dialog.confirm('Do you want to exit ?', 'Confirm Exit');
result.done(function (dialogResult) {
try {
if (dialogResult === true) {
navigator.app.exitApp();
}
}
catch (e) {
DevExpress.ui.dialog.alert(e.message, 'Exception');
}
});
}
this works fine in android but not working in windows phone.
how can I close an application programetically in windows phone 8 ??
The exitApp method is not supported by Cordova APIs for Windows Phone 8. To solve the problem, please execute the following code for the Windows Phone 8 platform:
window.external.Notify("DevExpress.ExitApp");
If you create a Windows Phone application using the DevExtreme wizard, the required code will be automatically generated.
if(device.platform === "win8" && device.phone) {
defaultLayout = "simple";
startupView = "Navigation";
$.each(Application1.config.navigation, function (i, item) { item.root = false; });
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
}
function onBackKeyDown() {
if(Application1.app.canBack()) {
Application1.app.back();
}
else {
if(window.external) {
window.external.Notify("DevExpress.ExitApp");
}
}
}
Thanks,

XMLHttpRequest to send a GET HTTP request with an username/password

I develop a Chrome uses XMLHttpRequest to send a GET HTTP request with an username/password to a basic-auth-protected URL, so that it can then "auto-login" to it afterwards (since Chrome caches credentials for HTTP basic-auth).
Here's the code I use:
var xml = new XMLHttpRequest();
xml.open('GET',<url>,false,<username>,<password>)
xml.send('');
After some additional research, I found out that it might have to do with Chrome 19 not supporting the username:pwd#url syntax for authenticating to basic-auth protected URLs, because when I send the XMLHttpRequest, I see this in Google Chrome's js console:
GET http://user:pass#domain.com 401 (Unauthorized)
Does anyone know whether it's a bug or if Chrome stopped supporting this feature?
My function
function autoLogin(domain, user, password) {
var httpAuth;
if (window.XMLHttpRequest) {
httpAuth = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}
else if (window.ActiveXObject) {
httpAuth = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
else {
alert("Seu browser não suporta autenticação xml. Favor autenticar no popup!");
}
var userName = domain + "\\" + user;
httpAuth.open("GET", "/_layouts/settings.aspx", false, userName, password);
httpAuth.onreadystatechange = function () {
if (httpAuth.status == 401) {
alert("Usuário e/ou senha inválidos.");
eraseCookie('AutoLoginCookieUserControl_User');
eraseCookie('AutoLoginCookieUserControl_Password');
}
else {
if ($(".pnlLogin").is(':visible')) {
$(".pnlLogin").hide();
$(".pnlUsuario").css("display", "block");
$(".avatar").css("display", "block");
var name = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });
$(".loginNomeUsuario").html("Seja Bem Vindo(a) <br />" + name);
}
}
}
var userAgent = navigator.userAgent.toLowerCase();
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
if ($.browser.chrome == true) {
httpAuth.setRequestHeader("Authorization", "Basic " + btoa(userName + ":" + password));
}
try {
httpAuth.send();
}
catch (err) {
console.log(err);
}
}
You need to add headers to the XHR request manually.
xml.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password))
Demo here: http://jsbin.com/inuhiv/2 (NOte, there is nothing to auth, however look at devtools and see the request has auth header)