I am making a chrome extension, and I am using chrome storage to store a variable. Actually I am first inputing a timer from user, and then refreshing the page after every T seconds those are given as input by user. So to store this time I used chrome storage like this :
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
var currentTimer = request.timer;
if(currentTimer!=null){
currentTimer = currentTimer*1000;
alert(currentTimer);
chrome.storage.sync.set({'x': currentTimer}, function() {
console.log(currentTimer);
});
}
if(currentTimer==null){
chrome.storage.sync.get('x', function(items){
currentTimer = items.value;
});
//Here currentTimer is undefined.
}
});
Can anyone help why currentTimer is still undefined. I am debugging for very long time, but could not arrive at a solution.
The problem is that as soon as page is refreshed currentTimer will get NULL value as it is been entered only once by user.
All chrome.* API callbacks are invoked asynchronously when the originating function has already finished, which also means that the next statement after chrome.* API call is executed before the callback.
Put the code that needs the result into the callback:
chrome.storage.sync.get('something', function(item) {
setTimeout(someFunction, item.value);
});
In case the result is needed in a content script, return the value in a new message:
content script:
chrome.runtime.sendMessage({request: "doSomething"});
chrome.runtime.onMessage.addListener(function(msg) {
if (msg.response) {
// do something with the received msg.response
}
});
background script:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.request == "doSomething") {
var tabId = sender.tab.id, frameId = sender.frameId;
chrome.storage.sync.get('something', function(item) {
sendMessageToFrameId(tabId, frameId, {response: item.value});
});
}
});
function sendMessageToFrameId(tabId, frameId, msg) {
// 1. frameId works since Chrome 41 and throws on prior versions
// 2. without frameId Chrome 45 sends the message to wrong tabs
try { chrome.tabs.sendMessage(tabId, msg, {frameId: frameId}); }
catch(e) { chrome.tabs.sendMessage(tabId, msg); }
}
Related
I'm using web BLE. I have based my code according to the example of the heart rate measurement.
Everything is working fine most of the time. But sometimes, even if the connection is successfully made, when I try to bind to the notification, it doesn't work.
The link is made in this function :
_startNotifications(characteristicUuid) {
let characteristic = this._characteristics.get(characteristicUuid);
console.log(characteristic);
return characteristic.startNotifications().then(() => characteristic);
}
When everything is OK, I can see in the console that BluetoothRemoteGATTCharacteristic has a value : DataView(2) {}
Otherwise, when it's not working it has a value : null
I would like to be able to retry automatically, if I detect that the value is null. But I'm not familiar with Promise (I think this is it) and console.log(characteristic.value) doesn't work here.
How would you approach this ?
What I ended up doing is "bypass" the issue. So it's a more algorithmic resolution than a pure Javascript one.
I didn't change the connection function, so it is still called like this :
device._startNotifications(some_uuid).then(handleHeartRateMeasurement)
I check everything in the handleHeartRateMeasurement function :
var ready = false;
function handleHeartRateMeasurement(heartRateMeasurement) {
console.log("Hold on...");
heartRateMeasurement.addEventListener("characteristicvaluechanged", event => {
// Everytime the value change, this should be triggered
// If it did not, variable "ready" will stay false
ready = true;
var value = device.parseValue(event.target.value);
// Do something with value here
});
var check = function(){
// If we have received data from characteristic, we are ready to go !
if(ready === false){
console.log("Device connected but not receiving data");
// Stop the current notification subscription
device.stopNotificationsHeartRateMeasurement();
// Start a new one
device._startNotifications(some_uuid).then(handleHeartRateMeasurement);
setTimeout(check, 1000); // check again in a 1s
}
else{
console.log("Device connected and receiving data");
}
}
setTimeout(() => {
check();
}, 500);
}
Something about my use of chrome.hid.send seems to be leaving the bus in a bad state. I consistently can NOT get my second usage of the API call to work. Sometimes, it will also fail on the first usage. WITH THE EXACT SAME CODE, I can come back and try a while later (maybe 10min) and the first send will work.
The device I'm working with does not return a response to all messages sent to it. The test message for example, is just a dummy message that is ignored by the device. I've tested this both on a mac and a PC. My call stack depth is 2 at this point in my application (literally first one is kicked off by a button click and then a setTimeout calls the same method 5s later).
I've testing sending buffers of length 64Bytes as well as 58Bytes. The properties from the HidDeviceInfo object read "maxInputReportSize":64,"maxOutputReportSize":64
Params on first usage:
Params on second usage:
I really can't identify how I'm using the API incorrectly. When messages do succeed, I can see them on the device side.
// Transmits the given data
//
// #param[in] outData, The data to send as an ArrayBuffer
// #param[in] onTxCompleted, The method called on completion of the outgoing transfer. The return
// code is passed as a string.
// #param[in] onRxCompleted, The method called on completion of the incoming transfer. The return
// code is passed as a string along with the response as an ArrayBuffer.
send: function(outData, onTxCompleted, onRxCompleted) {
if (-1 === connection_) {
console.log("Attempted to send data with no device connected.");
return;
}
if (0 == outData.byteLength) {
console.log("Attempted to send nothing.");
return;
}
if (COMMS.receiving) {
console.log("Waiting for a response to a previous message. Aborting.");
return;
}
if (COMMS.transmitting) {
console.log("Waiting for a previous message to finish sending. Aborting.");
return;
}
COMMS.transmitting = true;
var dummyUint8Array = new Uint8Array(outData);
chrome.hid.send(connection_, REPORT_ID, outData, function() {
COMMS.transmitting = false;
if (onTxCompleted) {
onTxCompleted(chrome.runtime.lastError ? chrome.runtime.lastError.message : '');
}
if (chrome.runtime.lastError) {
console.log('Error in COMMS.send: ' + chrome.runtime.lastError.message);
return;
}
// Register a response handler if one is expected
if (onRxCompleted) {
COMMS.receiving = true;
chrome.hid.receive(connection_, function(reportId, inData) {
COMMS.receiving = false;
onRxCompleted(chrome.runtime.lastError ? chrome.runtime.lastError.message : '', inData);
});
}
});
}
// Example usage
var testMessage = new Uint8Array(58);
var testTransmission = function() {
message[0] = 123;
COMMS.send(message.buffer, null, null);
setTimeout(testTransmission, 5000);
};
testTranmission();
The issue is that Windows requires buffers to be the full report size expected by the device. I have filed a bug against Chromium to track adding a workaround or at least a better error message to pinpoint the problem.
In general you can get more detailed error messages from the chrome.hid API by enabling verbose logging with the --enable-logging --v=1 command line options. Full documentation of Chrome logging is here.
I'm using WebSockets to connect to a remote host, and whenever I populate realData and pass it to grapher(), the JavaScript console keeps telling me realDatais undefined. I tried checking the type of the data in the array, but it seems to be fine. I've called grapher() before using an array with random data, and the call went through without any problems. With the data from the WebSocket, however, the call will always give me "error: realData is not defined". I'm not sure why this is happening. Here is the code I used:
current.html:
var command = "Hi Scott"
getData();
function getData()
{
console.log("getData is called");
if("WebSocket" in window)
{
var dataCollector = new WebSocket("ws://console.sb2.orbit-lab.org:6100",'binary');
dataCollector.binaryType = "arraybuffer";
console.log(dataCollector.readyState);
dataCollector.onopen = function()
{
//alert("The WebSocket is now open!");
console.log("Ready state in onopen is: " + dataCollector.readyState);
dataCollector.send(command);
console.log(command + " sent");
}
dataCollector.onmessage = function(evt)
{
console.log("onmessage is being called");
var realData = new Uint8Array(evt.data);
console.log(realData);
grapher(realData); //everything up to this point works perfectly.
}
dataCollector.onclose = function()
{
alert("Connection to Server has been closed");
}
return (dataCollector);
}
else
{
alert("Your browser does not support WebSockets!");
}
}
graphing.js:
function grapher(realData)
{
console.log("grapher is called");
setInterval('myGraph(realData);',1000); //This is where the error is. I always get "realData is not defined".
}
function myGraph(realData)
{
/*
for(var i = 0; i < SAarray.length; i++) // Loop which will load the channel data from the SA objects into the data array for graphing.
{
var data[i] = SAarray[i];
}
*/
console.log("myGraph is called");
var bar = new RGraph.Bar('channelStatus', realData);
bar.Set('labels', ['1','2','3','4','5','6','7','8']);
bar.Set('gutter.left', 50);
bar.Set('gutter.bottom', 40);
bar.Set('ymax',100);
bar.Set('ymin',0);
bar.Set('scale.decimals',1);
bar.Set('title','Channel Status');
bar.Set('title.yaxis','Status (1 is on, 0 is off)');
bar.Set('title.xaxis','Channel Number');
bar.Set('title.xaxis.pos',.1);
bar.Set('background.color','white');
bar.Set('colors', ['Gradient(#a33:red)']);
bar.Set('colors', ['red']);
bar.Set('key',['Occupied','Unoccupied']);
bar.getShapeByX(2).Set('colors',barColor(data[0]));
bar.Draw();
}
Because strings (as code) passed to setInterval execute in the global scope, therefore the realData parameter isn't available. There's rarely a good reason to pass a string to setInterval. Instead, use:
setInterval(function () {
myGraph(realData);
}, 1000);
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
Try it without it needing to evaluate a string:
setInterval(function() {
myGraph(realData);
},1000);
Any time you are using setTimeout or setInterval, you should opt for passing an actual function instead of a string.
Using the gapi.auth.authorize function, the user can close the popup without clicking any option (no accept or deny button). When this case happens, my callback function doesn't fire, so that I can't handle this case. What's the way to resolve this scenario?
Thanks.
This question has been around for a while, but when I looked into the issue (I want to show a spinner while the google authentication window is open, and hide it if the user decides not to authenticate), and found that gapi is throwing an error popup_closed_by_user. There is a two-second delay (which is kind of long, Facebook's is instant) before it is thrown, but it does work. Hooray, Google!
Some sample code (angular 1.x), prompting is the attribute to show the spinner:
_google_obj.prompting = true;
gapi.auth2.getAuthInstance().signIn().then(function(googleResponse){
var token = googleResponse.getAuthResponse().id_token;
SVC_exec_.post('/q/goog', 1000, { token: token }, 'signing you in through Google', function (response) {
if (response.code === 'ok') {
// update the UI
}
_google_obj.prompting = false;
});
},
function(error){
$timeout(function () {
console.log('user probably closed the google popup window: '+error);
_google_obj.prompting = false;
});
});
They don't appear to mention it in any documentation, but gapi.auth.authorize() returns the popup Window. So you can save the returned Window and set an interval or timeout to check Window.closed.
So you the auth function from Google returns promise, not a window. But then you can wrap original window into the function, which will set interval, to check if opened window closed already.
// variable to store our deferred object
var authDefer = null;
function auth() {
// right before the auth call, wrap window.open
wrap();
// Call auth
authDefer = window.gapi.auth.authorize({
client_id: ...,
scope: ...,
immediate: ...
}).then(
// onSuccess,
// onReject,
// onNotify
);
}
function wrap() {
(function(wrapped) {
window.open = function() {
// re-assign the original window.open after one usage
window.open = wrapped;
var win = wrapped.apply(this, arguments);
var i = setInterval(function() {
if (win.closed) {
clearInterval(i);
if (authDefer) {
authDefer.cancel();
}
}
}, 100);
return win;
};
})(window.open);
}
Taken from one of the thread on Google forums. Really works.
External link to Source
I am writing a chat AJAX app. Randomly, in FF 3.5.9, setInterval() seems to stop firing. I don't have clearInterval() anywhere in my code. What could be causing this to happen?
$(document).ready(function () {
$("#no-js-warning").empty();
messageRefresher = new MessageRefresher(0);
setInterval($.proxy(messageRefresher, "refresh"), 2000);
});
function notifyInRoom(user) {
$.getJSON('API/users_in_room', { room_id: $.getUrlVar('key'), username: user }, function (users) {
if (!$.isEmptyObject(users)) {
$("#users").empty();
$.each(users, function (index, username) {
var newChild = sprintf("<li>%s</li>", username);
$("#users").append(newChild);
});
}
else {
$("#users-loading-msg").text("No one is in this room.");
}
});
}
function MessageRefresher(latest_mid) {
this._latest_mid = latest_mid;
}
MessageRefresher.prototype.refresh = function () {
notifyInRoom($("#user-name").val());
var refresher = this;
$.getJSON('API/read_messages', { room_id: $.getUrlVar('key'), mid: refresher._latest_mid }, function (messages) {
if (! (messages == null || $.isEmptyObject(messages[0]))) { // messages will always be at least [[], [], 0]
$("#messages-loading-msg").hide();
for (var i = 0; i < messages[0].length; i++) {
var newChild = sprintf('<li><span class="username">%s:</span> %s</li>', messages[1][i], messages[0][i]);
$("#messages").append(newChild);
}
refresher._latest_mid = messages[2];
setUserBlockClass();
}
else {
$("#messages-loading-msg").text("No messages here. Say anything...");
}
});
}
// Give the end-user-block class to the appropriate messages
// eg, those where the next message is by a different user
function setUserBlockClass() {
$("#messages li").each(function (index) {
if ($(this).children(".username").text() != $(this).next().children(".username").text()) {
$(this).addClass("end-user-block");
}
});
}
I checked the most recent responses in Firebug, and it was the same responses that had been sent earlier. (So, it's not like an unusual response caused a crash.)
If I refresh the page, the calls resume.
I'm setting breakpoints in Firebug while I develop, then unsetting them and hitting "continue". Is there any chance that this is causing the problem? UPDATE: With more testing, this seems like it might be the issue.
I'm also using the service in another browser, and the calls continue fine for it.
I'm seeing setInterval getting stopped when I debug with Firebug. Assume it's a timing/interrupt thing as it works fine as long as I'm not stepping over breakpoints.
One thing to check that I just ran into was that if you are checking whether setInterval works with something like:
console.log("X");
Firebug will only display the 'X' one time. Firebug appears to refuse to log the same text twice. However, testing in the Chrome console worked fine.
When I changed my test code to:
console.log(new Date());
Firebug gave me the results I expected.