like the question asks, I'm trying to communicate with a serial device through a chrome app, via a webpage. The objective is to turn on a switch with a button on a webpage, and make sure the switch is in fact on (serial response).
So far I have been able to turn on the switch fine, however I need to validate that it is in fact enabled.
My chrome app code:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.request == 'info') {
sendResponse(DEVICE_INFO);
} else if (request.request == 'turn_off') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('f');
}
});
//INSTEAD OF "OK" I NEED IT TO ASK THE DEVICE TO CONFIRM OFF/ON STATUS
sendResponse('OK');
} else if (request.request == 'turn_on') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('n');
}
});
sendResponse('OK');
}
return true;
});
If I send a "status" query to the device, it's going to take a few milliseconds for it to respond "off" or "on" to the serial buffer. Any ideas on how to go about this? Thanks in advance.
Ultimately I got it to work by requesting the device status within the listener block of code. Below are the modifications, crude but it gets the job done. DEVICE_STATUS is being updated by an onReceive listener on the serial connection.
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.request == 'info') {
sendResponse(DEVICE_INFO);
} else if (request.request == 'turn_off') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('f');
}
});
var time_loop = 0;
connection.send('s'); // s is for STATUS
var timer = setInterval(device_is_off, 200);
function device_is_off(){
if (time_loop > 5){ //Serial Communication Timeout at 1sec
sendResponse('ERROR ' + DEVICE_STATUS);
clearInterval(timer);
return;
}
if (DEVICE_STATUS == 0){
sendResponse('OK');
clearInterval(timer);
return
}
else time_loop++;
}
} else if (request.request == 'turn_on') {
device_array.forEach(function(device){
if (device.id == request.device_id){
device.send('n');
}
});
var time_loop = 0;
connection.send('s'); // s is for STATUS
var timer = setInterval(device_is_on, 200);
function device_is_on(){
if (time_loop > 5){
sendResponse('ERROR ' + DEVICE_STATUS);
clearInterval(timer);
return;
}
if (DEVICE_STATUS == 1){
sendResponse('OK');
clearInterval(timer);
return
}
else time_loop++;
}
}
return true;
});
Related
I have a navigator.permissions.query that is not working
function handlePermission() {
navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
report(result.state);
geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
report(result.state);
geoBtn.style.display = 'none';
navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
} else if (result.state == 'denied') {
report(result.state);
geoBtn.style.display = 'inline';
}
result.onchange = function() {
report(result.state);
}
});
}
function report(state) {
document.getElementById("t").innerHTML = ('Permission ' + state);
}
handlePermission();
I have a live example here please check out my code and tell me where I am going wrong
You should read the example again and the docs for the functions you're using. The error messages in you live example are pretty clear.
navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
You have to hand the correct/valid parameters to this function. revealPosition is a function which is run, when the user granted the geolocation, positionDenied is a function which is run, when the user denies the access to the geolocation and geoSettings is an object which includes the setting for the call to .getCurrentPosition.
So once you create the missing parameters instead of handing undefined references to the call the function will run just fine.
Now I have this code of redirect in function of the referer:
document.addEventListener('DOMContentLoaded', function() {
console.log(isMobile);
var referrer = document.referrer;
if(referrer.indexOf('site1.com') !== -1 || referrer.indexOf('site2.com') !== -1) {
if(isMobile.phone) {
window.location = "http://www.landingphone.com";
console.log('Is phone');
} else if(isMobile.tablet) {
window.location = "http://www.landingtablet.com";
console.log('Is tablet');
} else {
window.location = "http://www.landingdesktop.com";
console.log('Is desktop');
}
} else {
window.location = "http://www.anotherlanding.com";
}
});
Its ok this code for redirect in function of the referer site1 and site2.com, but if I need redirect also another referer (for example site3.com) to another landing (for example www.landingphone2.com, landingtablet2.com and landingdesktop2.com). What I need add in the code? what i need modify?
Thank you very much.
You can try something like this, adding another else if statement as referred to in the comment to your answer.
document.addEventListener('DOMContentLoaded', function() {
console.log(isMobile);
var referrer = document.referrer;
if (referrer.indexOf('site1.com') !== -1 || referrer.indexOf('site2.com') !== -1) {
if (isMobile.phone) {
window.location = "http://www.landingphone.com";
console.log('Is phone');
} else if (isMobile.tablet) {
window.location = "http://www.landingtablet.com";
console.log('Is tablet');
} else {
window.location = "http://www.landingdesktop.com";
console.log('Is desktop');
}
} else if (referrer.indexOf('site3.com') !== -1) {
// Do your other redirects here
} else {
window.location = "http://www.anotherlanding.com";
}
});
When I click the follow button, socket.io sends some data to the server, and then the server sends back a response number. According to what the number is, js alerts a message. But if I click the button a second time, js will alert the same message twice, and if I click it again, three times and so on. If I refresh the page, it starts all over again (click it once, alert shows up once, click it twice, alert shows up twice...)
Here's the code:
$('.followUser').click(function(e){
e.stopImmediatePropagation();
e.preventDefault();
var user= $(this).parent().parent().parent().parent().next().children().children('.userName').children().first().children().attr('id');
var thisUserId = $.cookie('thisUserID');
if(user != thisUserId){ //if he tries to follow himself
var object = {
user: user,
userId: thisUserId
}
socket.emit('followUser', object); //server just adds that user to the following list of the first user
socket.on('followUserResults', function(data){
if(data == 1){
alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
} else if(data == 0){
alert('User was added to your following list!');
} else if(data == 2){
alert('This user is already on your following list!');
}
});
} else {
return false;
}
Can you please help me with that? Thank you!
I am slightly unclear as to what is trying to be achieved but I've noticed an error in your code straight away.
This code should be outside of the $('.followuser').click function:
socket.on('followUserResults', function(data){
if(data == 1){
alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
} else if(data == 0){
alert('User was added to your following list!');
} else if(data == 2){
alert('This user is already on your following list!');
}
});
So your code should read like:
$('.followUser').click(function(e){
e.stopImmediatePropagation();
e.preventDefault();
var user= $(this).parent().parent().parent().parent().next().children().children('.userName').children().first().children().attr('id');
var thisUserId = $.cookie('thisUserID');
if(user != thisUserId){ //if he tries to follow himself
var object = {
user: user,
userId: thisUserId
}
socket.emit('followUser', object); //server just adds that user to the following list of the first user
} else {
return false;
}
socket.on('followUserResults', function(data){
if(data == 1){
alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
} else if(data == 0){
alert('User was added to your following list!');
} else if(data == 2){
alert('This user is already on your following list!');
}
});
Try put the socket.on(...) outside the click callback function, if still not working properly, I would need watch the server code.
I am trying to run some code when the browser back button is clicked.
How can i found out browser's back button with out changing the browser history?
I tried the code below.
I got an exception in the else block saying: "event is not defined".
window.onunload = HandleBackFunctionality();
function HandleBackFunctionality()
{
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked…");
} else {
alert("Browser refresh button is clicked…");
}
} else {
if(event.currentTarget.performance.navigation.type == 1)
{
alert("Browser refresh button is clicked…");
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Browser back button is clicked…");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
use
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
}
if (direction == 'forward') {
// do something else
}
});
Okay. Besides the fact that you should not initially trigger the event and to .unload = FunctionName and not .unload=FunctionName() and that you need to pass the event-argument I checked the code in the browser.
currentTarget is empty - this totally makes sense as there is no event-target like onclick but it is just the site reloading/unloading.
Please debug the code by yourself by using this and fit it to your needs:
window.onunload = HandleBackFunctionality;
function HandleBackFunctionality(event)
{
console.log(event, window.event);
}
You will see that currentTarget is not set (while event is).
This is the only solution that works for me with IOS safari.
<script>
window.addEventListener( "pageshow", function ( event ) {
var pagehistory = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( pagehistory ) {
// back button event - Do whatever.
}
});
</script>
I'm working on a chat app with Meteor and I don't want users to be able to copy/paste things into the form for obvious spam reasons. Is this possible? Here is the code I use to run the chat app:
Javascript:
// render all of our messages in the ui
Template.chatBox.helpers({
"messages": function() {
return chatCollection.find();
}
});
// get the value for handlerbar helper user
Template.chatMessage.helpers({
"user": function() {
if(this.userId == 'me') {
return this.userId;
} else if(this.userId) {
getUsername(this.userId);
return Session.get('user-' + this.userId);
} else {
return 'anonymous-' + this.subscriptionId;
}
}
});
// when Send Chat clicked at the message to the collection
Template.chatBox.events({
"click #send": function() {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
// check to see if the message has any characters in it
if (message.length < 1) {
alert("You must enter a message to post.");
return;
}
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//Validation
var bot =Check_bots();
if(bot==false)
{
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
alert("Slow down! No need to post that fast.");
return false;
}
},
"keypress #chat-message": function(e) {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
if (e.which == 13) {
//Validation
var bot =Check_bots();
if(bot==false)
{
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
console.log("you pressed enter");
e.preventDefault();
//repeat function from #send click event here
var message = $('#chat-message').val();
// check to see if the message has any characters in it
if (message.length < 1) {
alert("You must enter a message to post.");
return;
}
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
alert("Slow down! No need to post that fast.");
return false;
}
}
}
});
chatStream.on('chat', function(message) {
chatCollection.insert({
userId: this.userId,
subscriptionId: this.subscriptionId,
message: message
});
});
var lastintime=0;
var defference=0;
var msg_count=0;
function Check_bots()
{
var seconds = new Date().getTime() / 1000;
seconds=parseInt(seconds);
if(lastintime < seconds)
{
defference = seconds -lastintime;
lastintime=seconds;
if(defference<=5 && msg_count>=3)
{
return true;
}
else
{
return false;
}
}
}
I have no idea where to even start with this. How do you prevent copy/pasting?
It's not a good idea. Internet Explorer has a onpaste event, and there's been a convoluted implementation on Stack Overflow, but in general it's messy, crosses lines that generally shouldn't be crossed in web design, impossible to pull off completely across all browsers, and can be circumvented without too much trouble.
It's a far better idea to put character-rate limits and detect red flags for spam, like high link density and repetition.