How to connect to a SignalR hub from PhoneGap app on iOS? - javascript

I am attempting to build a PhoneGap iOS client for a basic SignalR chat server I have running (ASP.NET MVC 4). Everything works great when accessing it from a page in a browser but I just can't seem to get it to connect from the PhoneGap app. Here's the relevant parts of my code:
Server global.asax
protected void Application_Start()
{
// Register the default hubs route: ~/signalr * This must be registered before any other routes
RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
Server web.config
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
</system.webServer>
</configuration>
Server hub
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
PhoneGap client
<body>
<div data-role="page">
<div data-role="header">
<h1>Life As A Pixel</h1>
</div><!-- /header -->
<div data-role="content">
<label for="username">Name:</label>
<input type="text" name="username" id="username" value="" />
<label for="message">Message:</label>
<input type="text" name="message" id="message" value="" />
<br>
<input type="button" value="Send" id="sendmessage" />
</div><!-- /content -->
<div data-role="footer" data-position="fixed">
<h4></h4>
</div><!-- /footer -->
</div><!-- /page -->
<script type="text/javascript" src="cordova-2.7.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.3.1.js"></script>
<script type="text/javascript" src="js/jquery.signalR-1.0.0-rc1.min.js"></script>
<script type="text/javascript" src="http://www.mysite.com/signalr/hubs"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub
jQuery.support.cors = true;
$.connection.hub.url = 'http://www.mysite.com/signalr';
var chat = $.connection.chatHub;
alert(chat);
//alert(chat);
// Create a function that the hub can call to broadcast messages.
//chat.client.broadcastMessage = function (name, message) {
//$('#discussion').append('<li><strong>' + name
// + '</strong>: ' + message + '</li>');
//};
// Set initial focus to message input box.
//$('#message').focus();
// Start the connection.
$.connection.hub.start({ jsonp: true }).done(function () {
alert("connected");
$('#sendmessage').click(function () {
// Html encode display name and message.
var encodedName = $('<div />').text($('#username').val()).html();
var encodedMsg = $('<div />').text($('#message').val()).html();
// Call the Send method on the hub.
chat.send(encodedName, encodedMsg);
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
}).fail(function () {
alert("Failed to connect");
});
});
</script>
</body>
I've been through a ton of sites that talk about bits and pieces of it but can't get it figured out.
Thanks in advance,
Jason

I hope this helps. From here -> http://agilefromthegroundup.blogspot.com/2012/09/getting-signalr-and-phonegap-working.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Chat</title>
<link rel="stylesheet" href="jquery.mobile-1.0.1.css" />
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript" src="jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="http://jgough/SignalR/Scripts/jquery.signalR-0.5.3.js"></script>
<script type="text/javascript" src="http://jgough/SignalR/signalr/hubs"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<style type="text/css">
.ui-title
{
font-weight: bold;
}
</style>
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://jgough/SignalR/signalr";
// Grab the hub by name, the same name as specified on the server
var chat = $.connection.chat;
chat.addMessage = function (message) {
$('#chatMessages').append('<li>' + message + '</li>');
};
$.connection.hub.start({ jsonp: true });
$("#sendChatMessage").click(function () {
var message = $("#chatMessage").val();
console.log("Message: " + message);
chat.send(message);
});
});
</script>
</head>
<body>
<div id="home" data-role="page">
<div data-role="header">
<h1>
Chat!</h1>
</div>
<div data-role="content">
<h2>
Chat your heart out...</h2>
<div>
<textarea id="chatMessage"></textarea>
<br />
<a id="sendChatMessage" data-role="button">Send Chat Message</a>
</div>
<ul id="chatMessages">
</ul>
</div>
<div data-role="footer" data-position="fixed">
Thank you for chatting
</div>
</div>
</body>
</html>

Related

Socket.io stops emitting when any of the window is minimized

I'm trying to build a simple real time text editor that can be accessed and edited by a couple of collaborators at the very same time (not using any lock properties for now). It all works well, transmits live data - until I minimize any of the window (basically using two chrome windows to see the results) and socket stops emitting data.
Here are the server and client -
Server
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
users = [];
connections = [];
server.listen(4000);
console.log("server running");
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
io.sockets.on("connection", socket => {
//Connect
connections.push(socket);
console.log("connected: ", connections.length);
//Disconnect
socket.on("disconnect", data => {
connections.splice(connections.indexOf(socket), 1);
console.log("disconnected! left: ", connections.length);
});
//Send Message
socket.on('send message', data => {
console.log(data);
io.sockets.emit('new message', {msg: data});
});
});
Client
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Chat</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<div class="msgArea" id="msgArea">
<div class="row">
<div class="col-md-4">
<div>
<h3>RealTime Editor</h3>
<ul class="list-groups" id="users"></ul>
</div>
</div>
<div class="col-md-8">
<div class="chat" id="chat"></div>
<form action="" id="msg-form">
<div class="form-group">
<label for="">Enter below</label>
<textarea name="" id="msg" rows="15" class="form-control"></textarea>
<br />
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script src="/socket.io/socket.io.js"></script>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"
></script>
<script>
$(document).ready(() => {
console.log("connect");
const socket = io.connect();
let $msg = $("#msg");
socket.on("new message", data => {
// $chat.append('<div class="well">' + data.msg + "</div>");
$('#msg').text(data.msg);
});
$("#msg").on("change keyup paste", function() {
socket.emit("send message", $msg.val());
});
});
</script>
</html>

How do I fix the :ERR_BLOCKED_BY_CLIENT Error with Youtube Data Api V3 when displaying youtube videos using Iframe on the DOM?

I'm testing the Youtube Data API V3 to get a list videos by a query term and subsequently play them in an iframe.
I'm getting this error:
www-embed-player.js:306 GET https://googleads.g.doubleclick.net/pagead/id?exp=nomnom net::ERR_BLOCKED_BY_CLIENT
After some debugging and googling, I discovered that this error is often caused by adblockers. I've then disabled mine on Chrome and then retested the api call.
I no longer see the original error :ERR_BLOCKED_BY_CLIENT but my videos retrieved do not play. Player message: An error occurred, please try again later.
Below is the code. The JS is in the HTML file itself for simplicity.
Any help appreciated!
<!doctype html>
<html lang="en">
<head>
<title>Youtube API Test </title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
crossorigin="anonymous">
</head>
<style>
body {
background-color: #0F0F0F;
}
button.btn.btn-primary {
background-color: #E12523;
border-color: #E12523;
}
div.jumbotron {
background-color: #292929;
color: #B3B3B3;
}
hr.my-2 {
border: 1px solid #B3B3B3;
}
</style>
<body>
<div class="wrapper container">
<div class="jumbotron">
<h1 class="display-3">Youtube Api</h1>
<p class="lead">Let's use the Yotube Api to get videos</p>
<hr class="my-2">
<form>
<div class="form-group">
<label for="user-query"></label>
<input type="text" class="form-control" id="user-query" aria-describedby="emailHelp" placeholder="Search Youtube">
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
</div>
<div class="container" id="results"></div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ"
crossorigin="anonymous"></script>
<script type="text/javascript">
//Get Videos
$("#submit").on("click", function (event) {
event.preventDefault();
var queryTerm = $("#user-query").val().trim();
$.ajax({
url: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + queryTerm + "&type=video&key=[MY API KEY]",
method: "GET"
}).then(function (data) {
console.log(data);
$.each(data.items, (i, item) => {
console.log(data.item);
const videoId = item.id.videoId;
let $iFrameContainer = $(`<iframe width="420" height="345" src="https://www.youtube.com/embed/"' ${videoId} '> <\/iframe >`);
$("#results").append($iFrameContainer);
})
});
})
</script>
</body>
</html>

SignalR MVC4 Issue

I am following this tutorial to integrate SignalR to my project http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/
So basically this is my View where I want to show my table.
#{
ViewBag.Title = "PatientInfo";
}
<h2>PatientInfo</h2>
<h3>#ViewBag.pName</h3>
<h5>#ViewBag.glucoseT</h5>
#if (Session["LogedUserFirstname"] != null)
{
<text>
<p>Welcome #Session["LogedUserFirstname"].ToString()</p>
</text>
#Html.ActionLink("Log Out", "Logout", "Home")
<div class="row">
<div class="col-md-12">
<div id="messagesTable"></div>
</div>
</div>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/SignalR/Hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
$.ajax({
url: '/home/GetMessages',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
</script>
}
My project is running but the table doesn't appear at all. I started by pasting the view because I believe that the scripts are not executed in the first place; The Alert Message is NOT being shown even if I try to add one directly after
$(function () {
alert("I am an alert box!");
This is my Layout.cshtml file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
</div>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#p_table").dataTable();
});
</script>
#RenderSection("scripts", required: false)
</body>
</html>
I am using Visual Studio 2012, MVC4.
Please Help..
Make sure you have placed all your script tags from the view inside the scripts section of the view:
#section scripts {
... your <script> tags come here
}
The reason why your alerts don't work is because you have directly put them inside the body of the view which gets rendered at the #RenderBody() call of the Layout. But as you can see it's only at the end of this Layout that we have references to the scripts such as jQuery and signalr.
Now they will appear at the proper location: #RenderSection("scripts", required: false).
By the way use the console window in your webbrowser to see potential script errors you might have. For example in your case it would display that jQuery is not defined error.
Another remark: don't include signalR script twice: right now you seem to have included jquery.signalR-2.2.0.js in your view and jquery.signalR-2.2.0.min.js in your Layout.

how to solve the error " Uncaught TypeError: Cannot call method 'changePage' of undefined"

I am just a beginner in phonegap as well as in javascript so while making a simple app for example, i wrote the following code in the index.html head and my main.js file is not getting included while i run the code. I hope anyone could help me out with the problem.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0rc2.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0rc2.js"></script>
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
</head>
<body onload="init()">
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Welcome to Phonegap</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<script>
$("#loginPage").live("pageinit", function(e) {
checkPreAuth();
});
</script>
</body>
</html>
here is the main.js file code as well.I just want only a particular login id to be valid.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
navigator.notification.alert("You entered a username and password");
handleLogin();
}
}
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var u = $("#username", form).val();
var p = $("#password", form).val();
var str1 = "burden123";
var str2 = "game1234";
var n1 = str1.localeCompare(u);
var n2 = str1.localeCompare(p);
if(u != '' && p!= '') {
$.post("http://www.coldfusionjedi.com/demos/2011/nov/10/service.cfc? method=login&returnformat=json", {username:u,password:p}, function(res) {
if(n1==0 && n2==0) {
$.mobile.changePage("some.html");
} else {
navigator.notification.alert("Your login failed", function() {});
}
$("#submitButton").removeAttr("disabled");
},"json");
} else {
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
this line in your code should be changed to
<script type="text/javascript" charset="utf-8" src="main.js"></script>
as main js is in same folder of index.html page.
<script type="text/javascript" charset="utf-8" src="assests/www/main.js"></script>
in above check you path in src also try putting it above and place a alert at top in main.js
check if all scripts above this is including or not.
Thanks

getJSON works on Android but Not IOS

I am testing getting some json and the json code actually shows on my Android but when I try it on my iPhone it won't work.
Is there anything extra that needs setting for IOS ?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>JSON Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile-1.1.1.min.css" />
<script src="js/jquery-1.7.1.min.js"></script>
<script>
$('#page1').live("pageinit", function () {
$.getJSON("http://mysite.com/api/get_cats", function (data) {
var output = '';
$.each(data.cats, function (index, value) {
output += '<li>' + value.title + '</li>';
});
$('#listview').append(output).listview('refresh');
});
});
</script>
<script src="js/jquery.mobile-1.1.1.min.js"></script>
</head>
<body>
<div id="page1" data-role="page">
<div data-role="header">
<h1>Page Title</h1>
</div><!-- /header -->
<div data-role="content">
<p>Page content goes here.</p>
<ul id="listview"></ul>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
</body>
</html>
If I add an alert: alert(data.cats); I get "index.html [object: Object]" in the iphone"
Any ideas anyone?
Do you have that domain whitelisted ?
It's in config.plist...while on android it's in cordova.xml
See http://docs.phonegap.com/en/2.0.0/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide
EDIT:
You can alert things from respons jqxhr object as well to find out more. As a response function add another two parameters
function(data, textStatus, jqXHR){...}

Categories