Firefox plugin for SSL - javascript

I am trying to make a plugin for Mozilla which prints simple SSL details like Name and certificate is valid till what date.
Here is my CODE :
var data = require("sdk/self").data;
var text_entry = require("sdk/panel").Panel({
width: 412,
height: 400,
contentURL: data.url("text-entry.html"),
contentScriptFile: data.url("get-text.js")
});
require("sdk/widget").Widget({
label: "Text entry",
id: "text-entry",
contentURL: "http://www.mozilla.org/favicon.ico",
panel: text_entry,
});
text_entry.on("show", function() {
text_entry.port.emit("show");
});
text_entry.port.on("text-entered", function (text) {
console.log(text);
var requrl = require("sdk/tabs").activeTab.url;
console.log(requrl);
const {Ci,Cc} = require("chrome");
//var req = new XMLHttpRequest();
var req = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
req.open('GET', requrl, false);
req.onload = function(e) {
console.log(req);
let channel = req.channel;
console.log(requrl);
if (! channel instanceof Ci.nsIChannel) {
console.log("No channel available\n");
return;
}
console.log(requrl);
var secInfo = req.securityInfo;
var cert = secInfo.QueryInterface(Ci.nsISSLStatusProvider).SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert ;
var validity = cert.validity.QueryInterface(Ci.nsIX509CertValidity);
console.log(requrl);
console.log("\tCommon name (CN) = " + cert.commonName + "\n");
console.log("\tOrganisation = " + cert.organization + "\n");
console.log("\tIssuer = " + cert.issuerOrganization + "\n");
console.log("\tSHA1 fingerprint = " + cert.sha1Fingerprint + "\n");
console.log("\tValid from " + validity.notBeforeGMT + "\n");
console.log("\tValid until " + validity.notAfterGMT + "\n");
};
});
It says, XMLHttpRequest is not defined. Also the channel structure is empty when printed to console.

Not exactly sure where your code is broken or why (as I'm to lazy to replicate the missing pieces like the text-entry.html).
Anyway, here is a fast test that works for me in both, and SDK add-on and Scratchpad:
// Save as your main.js.
// Alternatively execute in a Scratchpad in about:newTab.
var sdk = false;
if (!("Cc" in this)) {
try {
// add-on SDK version
this.Cc = require("chrome").Cc;
this.Ci = require("chrome").Ci;
this.log = console.error.bind(console);
this.sdk = true;
log("using SDK");
}
catch (ex) {
// Scratchpad on about:newtab version
this.Cc = Components["classes"];
this.log = console.log.bind(console);
log("using scratchpad");
}
}
let r = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
r.open("GET", "https://tn123.org/");
r.onloadend = function(e) {
let ok = "OK";
try {
log(e);
// Note: instanceof is an implicit QueryInterface!
log(this.channel instanceof Ci.nsIChannel);
log(this.channel.securityInfo instanceof Ci.nsISSLStatusProvider);
let status, cert;
log(status = this.channel.securityInfo.SSLStatus);
log(status.cipherName);
log(cert = status.serverCert);
log("Common name (CN) = " + cert.commonName);
log("Organisation = " + cert.organization);
log("Issuer = " + cert.issuerOrganization);
log("SHA1 fingerprint = " + cert.sha1Fingerprint);
log("Valid from " + cert.validity.notBeforeGMT);
log("Valid until " + cert.validity.notAfterGMT);
for (let k of Object.keys(cert)) {
if (k[0].toUpperCase() === k[0]) {
// skip constants
continue;
}
let v = cert[k];
if (typeof v === "function") {
continue;
}
log(k + ": " + v);
}
}
catch (ex) {
log("Caught exception", ex);
ok = ex;
}
if (sdk) {
require("notifications").notify({
title: "Test done",
text: "HTTPS test done; result=" + ok
});
}
log("HTTPS test done; result=" + ok);
};
r.send();
PS: I'm using console.error in the SDK, because:
If you're developing your add-on using the Extension Auto-installer,
then the add-on is installed in Firefox, meaning that messages will
appear in the Browser Console. But see the discussion of logging
levels: by default, messages logged using log(), info(), trace(), or
warn() won't be logged in these situations.

Have you written this in the content script? If so, you can't make requests from the content script (which is why it says it does not exist). You need to write this in main.js. If you want to communicate with your content script (html, window, etc) you'll have to use message passing: port.emit and addon.emit to send messages and port.on and addon.on to listen for messages.

Related

Store webkitSpeechRecognition in browser (indexeddb)

For a project I've implemented a web speech api in a website/Progressive Web App which translates spoken voice to text. This all works fine, however, I would also like to use this without access to internet.
My initial thought was that I could save my recognition object to a indexeddb and process it later. However, when I try to do this I get the following error:
DOMException: Failed to execute 'put' on 'IDBObjectStore': SpeechRecognitionEvent object could not be cloned.
While I do understand why I get this error, I have no clue on any alternative way of doing this or how I can solve this error.
My object looks as following:
When I try to serialize my object using JSON.stringify() I get the following:
I lose all of my information.
My code looks as follows:
function attachRecognition() {
recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.onstart = function(event) {
recognitionStarted = true;
};
recognition.onend = function(event) {
recognitionStarted = false;
};
recognition.onresult = function(event) {
var finalPhrase = '';
var interimPhrase = '';
var result;
for(var i=0; i<event.results.length; ++i) {
result = event.results[i];
if( result.isFinal ) {
finalPhrase = finalPhrase.trim() + ' ' + result[0].transcript;
}
else {
interimPhrase = interimPhrase.trim() + ' ' + result[0].transcript;
}
}
var input_field = $(related_input_field);
if (connected) {
input_field.val(input_field.val() + finalPhrase + ".");
}
// This is where I would store my event data in case there's no connection.
else {
set(related_input_field.attr("id"), event)
.then(() => {
console.log(related_input_field.attr("id") + ' data cached');
})
.catch(console.warn);
}
}
}
How can I solve this?

Phonegap: FileTransferError.FILE_NOT_FOUND_ERR

I'm using the Phonegap file transfer plugin to upload a picture to the server. However I am getting error code: 1 (FileTransferError.FILE_NOT_FOUND_ERR). I've tested my server code with POSTMAN and I can upload and image successfully. However I get that error with the plugin. This is my code. The file is declared from "camera_image.src" and I can see the image when I append this to the src of an image on the fly. Any contributions? How is this code not perfect?
var fileURL = camera_image.src;
alert(fileURL);
var win = function (r) {
temp.push(r.response);
statusDom.innerHTML = "Upload Succesful!";
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code + " | Source:" + error.source + " | Target:" + error.target );
statusDom.innerHTML = "Upload failed!";
}
var options = new FileUploadOptions();
options.fileKey = "properties_photo";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.headers = {
Connection: "close"
};
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
statusDom = document.querySelector('#status');
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
statusDom.innerHTML = perc + "% uploaded...";
console.log(perc);
} else {
if(statusDom.innerHTML == "") {
statusDom.innerHTML = "Loading";
} else {
statusDom.innerHTML += ".";
}
}
};
ft.upload(fileURL, encodeURI("http://cloud10.me/clients/itsonshow/app/image_upload_process.php"), win, fail, options);
I had this problem because of spaces in the path or filename of the file to be uploaded.
You need to ensure the plugin isn't being passed a fileURL with %20 in the URL.

How to override method on Window in ES2015

I'm trying to rewrite an vanilla ES5 closure to a ES2015 Class. The code overrides the window.onerror function and acts as a global error handler method for logging purposes.
My old code looks like this. I would like to know how to rewrite it in ES2015. How do i override the Window.onerror?
(function() {
window.onerror = function(errorMessage, url, line) {
try {
if (typeof(url) === "undefined") {
url = "";
}
if (typeof(line) === "undefined") {
line = "";
}
// Avoid error message being too long...
if (errorMessage.length > 300) {
errorMessage = errorMessage.slice(0,300) + "...";
}
errorMessage = errorMessage.replace(/&/g, "%26").replace(/ /g, "+");
url = url;
line = line;
var parentUrl = encodeURIComponent(document.location.href);
// Set error details
var parameters = "error_message=" + errorMessage +
"&url=" + url +
"&line=" + line +
"&parent_url=" + parentUrl;
// Set path to log target
var logUrl = "xxx";
// Set error details as image parameters
new Image().src = logUrl + '?' + parameters;
} catch (e) {}
};
}());
EDIT!
Now I'm trying to rewrite it in a JS Class. So I guess I have to extend the Window class or something like that (I have a Java background). But Window is not a class as I understand. This is what I have so far.
So I need help to override the window.onerror function, written in ES2015!
export const Logging = new class {
constructor() {
// todo
}
onerror(errorMessage, url, line) {
try {
if (typeof(url) === "undefined") {
url = "";
}
if (typeof(line) === "undefined") {
line = "";
}
// truncate error message if necessary
if (errorMessage.length > 300) {
errorMessage = errorMessage.slice(0,300) + "...";
}
// URI encoding
errorMessage = errorMessage.replace(/&/g, "%26").replace(/ /g, "+");
url = url;
line = line;
var parentUrl = encodeURIComponent(document.location.href);
// set error details
var parameters = "error_message=" + errorMessage +
"&url=" + url +
"&line=" + line +
"&parent_url=" + parentUrl;
// Set path to log target
var logUrl = "xxx";
// set error details as image parameters
var img = new Image().src = logUrl + '?' + parameters;
console.log(img);
}
catch (e) {}
}
}
/* ------------------------------------------------------------------------------------------------------------ */
export default Logging;
The only thing that might be useful here are parameter default values. Everything else that I changed was mistaken in ES5 already.
window.onerror = function(errorMessage, url="", line="") {
try {
// Avoid error message being too long...
if (errorMessage.length > 303) {
errorMessage = errorMessage.slice(0,300) + "...";
}
var parentUrl = document.location.href;
// Set error details
var parameters = "error_message=" + encodeURIComponent(errorMessage).replace(/%20/g, "+") +
"&url=" + encodeURIComponent(url) +
"&line=" + encodeURIComponent(line) +
"&parent_url=" + encodeURIComponent(parentUrl);
// Set path to log target
var logUrl = "xxx";
// Set error details as image parameters
new Image().src = logUrl + '?' + parameters;
} catch (e) {}
};

I cannot send image in .net webservice using javascript

this is my Code Please help me this is my code... My web service in .net how i pass image using java script and get in .net Web service and store in Folder and get it back again. i had tried this Min. 3 hours but i failed to get solution please help me...
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('get picture failed'); },
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
alert(imageURI);
ft.upload(imageURI, encodeURI("http://www.gameworld.co.in/useImage"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
if you have other solution then please tell Me...
Thanks
You need to make use of function to get the actual path using
window.resolveLocalFileSystemURI(imguri, resolveOnSuccess, fsFail);
So your code would look like
var fileuri ="";
function uploadPhoto(imageURI) {
window.resolveLocalFileSystemURI(imageURI, resolveOnSuccess, fsFail)
var fileName = fileuri.substr(fileuri.lastIndexOf('/') + 1);
options.fileName = fileName;
// your remaining code
}
function resolveOnSuccess(entry) {
fileuri = entry.toURL();
//console.log(fileuri);
}
function fsFail(message) {
alert(message);
}

JavaScript: "Syntax error missing } after function body"

Ok, so you know the error, but why on earth am I getting it?
I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}
}
function Login() {
// Grab username and password for login
var uName = document.getElementById('uNameBox').value;
var pWord = document.getElementById('pWordBox').value;
ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}
function Chat() {
// Get username from recipient box
var user = document.getElementById('recipient').value;
self.location = 'index.php?to=' + user;
}
function SendMessage() {
// Grab message from text box
var from = readCookie('privateChat');
var to = getUrlVars()['to'];
var msg = document.getElementById('msgBox').value;
ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
// Reset the input box
document.getElementById('msgBox').value = "";
}
function GetMessages() {
// Grab account hash from auth cookie
var aHash = readCookie('privateChat');
var to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
var textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.
function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) { if(cmd == 'cmd=push') { document.getElementById('pushResponse').innerHTML = xmlObj.responseText; } if(cmd == 'cmd=pop') { document.getElementById('messages').innerHTML += xmlObj.responseText; } if(cmd == 'cmd=login') { if(xmlObj.responseText == 'OK') { self.location = 'index.php'; } else { document.getElementById('response').innerHTML = xmlObj.responseText; } } } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
You're missing a semi-colon:
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}; //<-- Love the semi
}
Additional missing semi-colon:
// Start checking of messages every second
window.onload = function() {
if (getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; //<-- Love this semi too!
I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.
This will help us to identify the actual point of error.
I do not see any problem with this script.
This may not be the exact solution you want, but it is a way to locate and fix your problem.
It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.
This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:
// Reset the input box
...to...
/* Reset the input box */
Adding a note: very strangely this error was there very randomly, with everything working fine.
Syntax error missing } after function body | At line 0 of index.html
It appears that I use /**/ and //🜛 with some fancy Unicode character in different parts of my scripts for different comments.
This is useful to me, for clarity and for parsing.
But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.
This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.
It seems there should be added another semicolon in the following code too:
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; <---- Semicolon added
Also here in this code, define the var top of the function
function readCookie(name) {
var i;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "
I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.

Categories