I am trying to get my proxy chrome extention to keep on/off after closing using chrome.local.storage. This does not seem to work, can anyone give some examples on how to get this kind of code working?
Right now my pac proxy works and turns on and off. The local storage does not seem to work at all, but I followed all the examples on the developer.chrome website. That does not work.
var channels;
var ny;
function endvpn() {
// turn off vpn
var config = {
mode: "pac_script",
pacScript: {
data: "function FindProxyForURL(url, host) {\n" +
" if (host == 'google.com /*')\n" +
" return 'PROXY blackhole:80';\n" +
" return 'DIRECT';\n" +
"}"
}
};
chrome.storage.local.set({ny: false});
// change vpn button
document.getElementById("vpnbtn").innerHTML = "Start Vpn";
// turn off event lisner for endvpn and start event listner to go back to startvpn
document.getElementById('vpnbtn').removeEventListener('click', endvpn, false);
document.getElementById("vpnbtn").addEventListener("click", startvpn);
}
function startvpn() {
// turn on vpn
var config = {
mode: "pac_script",
pacScript: {
data: "function FindProxyForURL(url, host) {\n" +
" if (host == 'google.com /*')\n" +
" return 'PROXY blackhole:80';\n" +
" return 'PROXY 209.127.191.180:80';\n" +
"}"
}
};
chrome.storage.local.set({ny: true});
// change vpn button
document.getElementById("vpnbtn").innerHTML = "Stop Vpn";
// turn off event lisner for startvpn and start event listner to go back to endvpn
document.getElementById('vpnbtn').removeEventListener('click', startvpn, false);
document.getElementById("vpnbtn").addEventListener("click", endvpn);
}
var rez = chrome.storage.local.get(ny);
alert(rez);
// start at startvpn
document.getElementById("vpnbtn").addEventListener("click", startvpn);
Most apis within Chrome extensions are asyncronous. See the documentation here. You can provide a callback as the second argument to the 'get' function where you can use the variable:
chrome.storage.local.get('ny', function(result){
alert(result.ny);
});
Related
In my application the following console error occurs when I navigate to another page.
Uncaught Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.
In layout page the scripts are in the following order.
#Styles.Render("~/Content/themes/base/jqueryUi")
#Styles.Render("~/Content/customCss")
#Scripts.Render("~/Scripts/jQuery")
#Scripts.Render("~/Scripts/customScripts")
<script src="/signalr/hubs"></script>
var progressHub = $.connection.parallelProcessing;
var flagDownload = true;
$(function() {
progressHub.client.updateProgresssBar = function(progressPercentage, downloadedSize, totalFileSize) {
debugger
downloadProgress("", "", "");
$("#downloading-progress").dialog("open");
var progressObj = $("#progressBar").data("ejProgressBar");
progressObj.option("text", progressPercentage + " %");
progressObj.option("percentage", progressPercentage);
$(".received").html("(" + downloadedSize + " ");
$(".total-size").html("of " + totalFileSize + ")");
flagDownload = true;
if (progressPercentage == 100)
$("#downloading-progress").dialog("close");
};
progressHub.client.noNetConnection = function() {
if (flagDownload) {
flagDownload = false;
showalertdownload("#Message.Nointernetconnection");
}
};
progressHub.client.closeProgressDialog = function() {
$("#downloading-progress").dialog("close");
enableEvents();
};
$.connection.hub.start().done(function () {
});
});
function updateConnectionID() {
progressHub.server.updateConnectionID();
}
Please let me know is ther any solution to resolve this issue.Thanks in advance.
Basing my answer on your error message, it seems you are trying to access your connection or hub without waiting for it to be initialized.
Taken from the ASP.NET SignalR Github wiki:
// This callback will only run once
connection.start().done(function() {
console.log("connection started!");
});
A more complete and detailed example to be found on ASP.NET website
I have a packaged chrome app having multiple windows. For example if I click a button in first window then a second window opened. Now how to send messages or commands to each other.
I have read a lot about it but did not figure out as i am very much new to this.
Any sample code will be very helpful.
There is a existing question How to communicate between multiple windows of the same chrome app?, but did not understand how to do it.
Thanks in advance!!!
You can use the postmessage method of a window, in order to send information to another window. By following this approach, you can execute a method from a window (A) on a different window (B). You'll need to create an event on window B that will inform A that the method ran correctly.
The code would be something like:
Sender:
//create popup window
var domain = 'http://scriptandstyle.com';
var myPopup = window.open(domain + '/windowPostMessageListener.html','myWindow');
//periodical message sender
setInterval(function(){
var message = 'Hello! The time is: ' + (new Date().getTime());
console.log('blog.local: sending message: ' + message);
myPopup.postMessage(message,domain); //send the message and target URI
},6000);
//listen to holla back
window.addEventListener('message',function(event) {
if(event.origin !== 'http://scriptandstyle.com') return;
console.log('received response: ',event.data);
},false);
Destination:
//respond to events
window.addEventListener('message',function(event) {
if(event.origin !== 'http://davidwalsh.name') return;
console.log('message received: ' + event.data,event);
event.source.postMessage('holla back youngin!',event.origin);
},false);
You can also find an in-dept explanation here: http://davidwalsh.name/window-postmessage
In the case of a Chrome app, the part about the domain is not required.
You need something as:
targetWindow = chrome.app.window.get("window-id").contentWindow;
targetWindow.postMessage(message, "*");
to send a message, while to receive:
window.addEventListener('message', function(event) {
var windowId = chrome.app.window.current().id;
console.log(windowId + ': received a message: ' + event.data, event);
var message = 'hello back!';
console.log(windowId + ': sending message: ' + message);
event.source.postMessage(message, event.origin);
});
I am doing pushnotification for both Android/IOS.
I have used a cordova push-plugin https://github.com/phonegap-build/PushPlugin, it seems to work great.
Info : I'm on a AngularJS project.
In my NotificationHelper factory i have this init method:
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};
I also defined those methods on mains.js :
var onNotificationGCM = function(event) {
// call back to web service in Angular.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var service = injector.get('NotificationHelper');
service.onNotificationGCM(event);
};
It's a trick to call angularJS factory from main javascript.
'onNotificationGCM' call the 'NotificationHelper.onNotificationGCM' method :
helper.onNotificationGCM = function(e) {
switch (e.event) {
case 'message':
// Notification happened while app was in the foreground
if (e.foreground) {
logger.debug('[notification] [message] Foreground : ' + JSON.stringify(e));
} else { // Notification touched in the notification tray
logger.debug('[notification] [message] Background : ' + JSON.stringify(e));
if (e.coldstart) {
// App was not running and user clicked on notification
} else {
// App was running and user clicked on notification
}
}
decriptPayloadNotification(e.payload);
break;
case 'registered':
logger.debug('[notification] [registered] : ' + JSON.stringify(e));
if (e.regid.length > 0) {
registerUser(e.regid, 'gcm');
}
break;
case 'error':
logger.debug('[notification] [error] : ' + JSON.stringify(e));
break;
default:
logger.debug('[notification] [default] : Unknown, an event was received and we do not know what it is : ' + JSON.stringify(e));
break;
}
};
During the first use, everything work good :
'Registered' event is received
Notifications are received
When i'm on foreground I receive 'message' event :
NotificationHelper: [notification] [message] Foreground : {"event":"message","from":"847593779913","message":"Agenêts 23/03 10h\r\n","collapse_key":"do_not_collapse","foreground":true,"payload":{"lt":"school","lv":"E1154","notId":"35429","title":"Agenêts le 23/03/2015","message":"Agenêts 23/03 10h\r\n"}}
When i'm on background, if i receive notif and touche it on notification tray, I receive 'message' event :
NotificationHelper: [notification] [message] Background : {"event":"message","from":"847593779913","message":"la piscine sera fermée 1 journée pour raison technique","coldstart":false,"collapse_key":"do_not_collapse","foreground":false,"payload":{"lt":"swimming pool","lv":"E114","notId":"29869","title":"23/04/2015 fermeture de la piscine","message":"la piscine sera fermée 1 journée pour raison technique"}}
BUT, if i kill my app, everything stop to work.
If i restart app, i will not receive anymore 'message'event and 'onNotificationGCM' will not be called.
I founded some articles speaking about this problem, but without success :
Stackoverflow : Phonegap PushNotification to open a specific app page
Does anyone has an idea about this problem ?
If you are using node-gcm as push notification server side I hope this might help for your question:
things to check:
use adb logcat from console and check your device logs to see if your device receives any notification (you should see some logs from gcmservices if you receive). I believe you should see some logs because otherwise you probably wouldn't get any notification when the app is on foreground either.
check if you add "title" and "message" keys on your message data (this draw me crazy before)
check if delayWhileIdle parameter is false
sample message variable and method i am using is below:
var pushAndroidSender = new gcm.Sender('Your GoogleApi Server Key Here');
var message = new gcm.Message({
collapseKey: 'demo',
delayWhileIdle: false,
timeToLive: 3,
data: {
"message":"What's up honey?",
"title":"Come on"
}
});
pushAndroidSender.send(message, registrationIds, function(err, result) {
if (err) {
console.error("this is an error: " + err);
} else {
console.log("this is a successful result:" + result);
}
});
I was asking myself why it worked correctly the first time and not the following times...and i had this idea :
maybe callback function is subscribed to plugin first time but not the next times.
And this is exactly the source of my problem. I call "pushNotification.register" only one time to init plugin and get ids...
But the next time I launch app, i don't instanciate again the plugin, so pushplugin don't know which method to call in callback request.
So answer is : Call "pushNotification.register" in each application launch !
In my code, i have to call method below on each "deviceready" event :
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};
I have simple project in ASP.NET Web site with signalr.
Code for start connection hub:
var scriptStarted = 'var myHub = $.connection.' + hubName + ';' + methodNameInitHub + '(myHub);';
$.connection.hub.error(function () {
alert("An error occured");
});
$.connection.hub.start()
.done(function () {
eval(scriptStarted);
myHub.server.registerClient($.connection.hub.id, clientIdentifier);
})
.fail(function () { alert("Could not Connect!"); });
This method is call in "methodNameInitHub + '(myHub);"
function methodInitEventHub(hub) {
if (hub) {
hub.client.addEvent = function (eventOperationName, eventType) {
$("#events").append("<li>" + eventOperationName + ", " + eventType + "</li>");
};
}
}
Code for stop connection hub:
$.connection.hub.stop();
When I load .aspx page and start hub all code execute without errors, but event from server not recieved.
After I stop and start again hub connection events begining received in client (browser)
http://clip2net.com/s/2CP2e
Why I need to restart connection hub for begin received event from server ?
Thanks.
The reason you're having issues is because you must have at least 1 client side hub function prior to calling start otherwise you will not be subscribed to the hub.
Try doing
myHub.client.foo = function() {}
prior to start.
The reason why it works after you stop then re-start the connection is because your script binds a new client method, hence allowing you to subscribe to the hub after you've restarted the connection.
Hope this helps!
We have an app that records audio, making use of the PhoneGap Media API and in iOS's case the File API.
When the user clicks the Accept & Upload button, the app moves that file to the server making use of PhoneGap's File.FileTransfer() method.
Works well with iOS, Android not so much.
When I connect my Android device to my computer and mount as a drive, I can see that the file is getting created at the root which is where it should be.
After the audio file has been created, I'm able to play the file on my device from the location stored in the global var fullRecordPath which = recording.wav
When I attempt to point File.FileTransfer() at that came path I'm getting Error Code = 1 which I understand is File Not Found
Code Handling the Accept & Upload tap event:
$('#btnAcceptUpload').live('tap',function () {
if(isIOS){
thisFileToUpload = fullRecordPath;
} else {
// thisFileToUpload = './'+fullRecordPath; //doesn't work
// thisFileToUpload = 'file:///'+fullRecordPath; //doesn't work
thisFileToUpload = fullRecordPath; //doesn't work
}
var options = new FileUploadOptions();
msg = '';
options.fileKey="file";
msg += "options.fileKey = "+options.fileKey+"\n";
options.fileName=thisFileToUpload.substr(thisFileToUpload.lastIndexOf('/')+1);
msg += "options.fileName = "+options.fileName+"\n";
options.mimeType='audio/wav';
options.chunkedMode = false;
msg += "options.mimeType = "+options.mimeType+"\n";
msg += "thisFileToUpload = "+thisFileToUpload;
alert(msg);
var ft = new FileTransfer();
ft.upload(thisFileToUpload, "http://10.0.17.121/~email/ttmovefiles.php", fileUploadSuccess, fileUploadFailure, options);
});
Success Callback:
function fileUploadSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
Failure Callback:
function fileUploadFailure(error){
alert("An error has occurred: Code = " + error.code);
}
Thanks for looking.
Alright, alright. I figured this one out. I promise I'll come back through and tighten this one down later, but wanted to get it documented so I might end helping another.
in iOS to create a new piece of media you have no choice, you gotta use the File api. This same fully qualified spot in the filesystem was moved in to the same global var which the Media.play() method played nicely with... in iOS.
Not sure why it works this way, but with Android, Media.play() doesn't like the fully qualified path passed in to it. It just wants the filename and it apparently searches from the root.
File.FileTransfer.upload() always wants the fully qualified path of the asset to upload, regardless iOS or Android.
To Make this work:
I used the File API to create the file that the audio Media then uses to move the recording in to. I set 2 global vars: one for playing the audio on the device fullRecordPath and the other for uploading fullUploadPath.
Here's the function the creates the file, invokes the media API and sets the global vars that Android wants:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile(recordFileName, {
create: true,
exclusive: false
}, function(fileEntry){
alert("---------> Android File " + recordFileName + " created at " + fileEntry.fullPath);
fullRecordPath = recordFileName;
fullUploadPath = fileEntry.fullPath;
mediaVar = new Media(recordFileName, function(){
alert("Android media created successfully");
}, androidMediaCreateFailure, mediaStatusCallback); //of new Media
onMediaCreated();
}, androidMediaCreateFailure); //of getFile
}, androidMediaCreateFailure); //of requestFileSystem
Here's the code to play that media back
function playAudio() {
var my_media = new Media(fullRecordPath,
// success callback
function () {
console.log("playAudio():Audio Success");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err.code);
exposeObject(err);
});
my_media.play();
}
Here's the code to upload
$('#btnAcceptUpload').live('tap',function () {
if(isIOS){
thisfullUploadPath = fullRecordPath;
} else {
thisfullUploadPath = fullUploadPath;
}
var options = new FileUploadOptions();
msg = '';
options.fileKey="file";
msg += "options.fileKey = "+options.fileKey+"\n";
options.fileName=thisfullUploadPath.substr(thisfullUploadPath.lastIndexOf('/')+1);
msg += "options.fileName = "+options.fileName+"\n";
options.mimeType='audio/wav';
options.chunkedMode = false;
msg += "options.mimeType = "+options.mimeType+"\n";
msg += "thisfullUploadPath = "+thisfullUploadPath;
alert(msg);
var ft = new FileTransfer();
ft.upload(thisfullUploadPath, "http://10.0.17.121/~email/ttmovefiles.php", fileUploadSuccess, fileUploadFailure, options);
});
On android you need to resolveFileSystem
window.resolveLocalFileSystemURI(FILEURI, function(msg){
// success call msg.fullPath
}, function(){
// FAIL
});