I am using the code below to get file-size of a remote file inside a Firefox Addon being developed using Mozilla Addon SDK.
main.js
// Import the page-mod API
var pageMod = require("sdk/page-mod");
// Import the self API
var self = require("sdk/self");
// Create a page mod
pageMod.PageMod({
include : "*.example.com",
contentScriptFile : [self.data.url("content.js"), self.data.url("jquery.min.js"), self.data.url("contentloaded.js")],
contentScriptWhen : "ready",
attachTo: ["top", "existing"],
onAttach : startListening,
contentScriptOptions : {
iconWait : self.data.url("wait.gif"),
iconFinished : self.data.url("done.png"),
}
});
function startListening(worker) {
worker.port.on("GetSize", function (data) {
// Handle the message
let getReq = require("sdk/request").Request({
url : data[0],
onComplete : function (response) {
reply = [response.headers["Content-Length"], data[1]];
//console.log("Send linkID : " + reply[1]);
worker.port.emit('receiveSize', reply);
}
}).head();
});
}
This works perfectly but the the DisplaySize function gets called multiple times for the same request.
content.js
function checkURL(url, linkID) {
data = [url, linkID];
self.port.emit("GetSize", data);
self.port.on("receiveSize", DisplaySize);
console.log("Inside checkURL For linkID : " + linkID); //<--This displays only once for each request
}
function DisplaySize(data) {
console.log("Inside DisplaySize For linkID : " + data[1]); //<--But this thrice
}
What am I missing here?
Each time you call port.on a new message listener is added. Only call it once.
function checkURL(url, linkID) {
data = [url, linkID];
self.port.emit("GetSize", data);
console.log("Inside checkURL For linkID : " + linkID);
}
function DisplaySize(data) {
console.log("Inside DisplaySize For linkID : " + data[1]);
}
self.port.on("receiveSize", DisplaySize);
Related
I am working on one chrome extension and i need to use local storage to send data from options page to background scritps.
Options page script:
function addToStorage(key, val){
let obj = {};
obj[key] = val;
chrome.storage.local.set( obj, function() {
if(chrome.runtime.lastError) {
console.error(
"Error setting " + key + " to " + JSON.stringify(val) +
": " + chrome.runtime.lastError.message
);
}
});
}
Background:
chrome.storage.local.get('code', function(code) {
... with code.code ...
});
For example:
Now chrome.storage.local code value is abcd
I'm performing addToStorage('code', '1234') from options page script
After that in background script value code only will change when i manually click "update" at chrome extesions page
How can i automatically get actual data at background script?
the background script will check only once when started as is.
You could pass a mesage from the options script to background scripts after you update the local storage and use that as a trigger to check storage.
try this:
Options page
function addToStorage(key, val){
let obj = {};
obj[key] = val;
chrome.storage.local.set( obj, function() {
if(chrome.runtime.lastError) {
console.error(
"Error setting " + key + " to " + JSON.stringify(val) +
": " + chrome.runtime.lastError.message
);
}
chrome.runtime.sendMessage({status: "Storage Updated"}, function (responce) {
console.log(responce);
})
});
}
Background Page:
chrome.runtime.onMessage.addListener(
function (request, sender, responce) {
if (request.status === "Storage Updated") {
chrome.storage.local.get('code', function(code) {
// ... with code.code ...
});
sendResponce({status: "Update Recieved"});
}
}
);
Hope that helps, message passing docs here: https://developer.chrome.com/extensions/messaging
Hello everyone I've tried everything I can think of to make this work. I know it does return stream = null or active through use in the browser, but It will not apply my buttons to my page. Not so good with javascript can anyone point me in the right direction.
<script type="text/javascript">
(function() {
var user_name, api_key;
user_name = "Undead_Atomsk";
api_key = "************************";
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.write(Live!);
} else {
document.write(Offline!);
}
});
})();
</script
Took your advice and used browser tools "Completely forgot about those".
I added this line to my html.
I then made a .js file and used the following code everything works now the twitch API is just slow!
(function() {
var user_name, api_key, twitch_widget;
user_name = "Undead_Atomsk";
api_key = "********************";
twitch_widget = $("#twitch-widget");
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.getElementById("twitch-btn").innerHTML = 'Live!';
} else {
document.getElementById("twitch-btn").innerHTML = 'Offline!';
}
});
})();
This question is edit for better undersatnding:
I am trying to use the cordova fileOpener2 plugin to open pdf files in my app's assets.
I obtain the file's uri thanks to lines 14 and onward of code below.
The uri is then stored as a varialbe (nonencodeduri).
However when I try to use the variable in the second part of the code where FileOpener2 needs the path to the file (from line 58), it stalls.
This is surprising because if I write hardcode the path to the same file line 58 (var uri = var uri = encodeURI("path to file in the assets of the app"), it works.
Thanks for helping me resolve this.
Here is the full code (credits: Ghandi)
var entry, documentname, documentid, referenceID, callLogID, filePath, blob,cdr,fileObject;
var filename = "test.pdf";
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
var fileURL = "";
var imagePath = "";
function onDeviceReady() {
sessionStorage.platform = device.platform;
var fileTransfer = new FileTransfer();
$('a[href$=\\.pdf]').click(function()
{
try {
alert('Hi boys');
var urinonencoded = this.href;
alert(urinonencoded + ' and voila');
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory,onFileSystemSuccess, onError);
}
else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,onFileSystemSuccess, onError);
}
}
catch(err) {
alert("ER - " + err.message);
}
});
function onError(e) {
alert("onError");
};
function onFileSystemSuccess(fileSystem) {
var entry="";
if (sessionStorage.platform.toLowerCase() == "android") {
entry=fileSystem;
}
else {
entry=fileSystem.root;
}
entry.getDirectory("Cordova", {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
};
function onGetDirectorySuccess(dir) {
dir.getDirectory("Sample_App", {create: true, exclusive: false}, onGetDirectorySuccess1, onGetDirectoryFail);
};
function onGetDirectorySuccess1(dir) {
cdr = dir;
dir.getFile(filename,{create:true, exclusive:false},gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
/*var uri = encodeURI(myref);*/
var uri = urinonencoded;
alert (uri);
alert("dest - " + cdr.nativeURL+filename);
fileTransfer.download(uri,cdr.nativeURL+filename,
function(entry) {
openFile();
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
alert("error");
},
true);
};
function openFile() {
alert("URL - " + cdr.nativeURL+filename);
cordova.plugins.fileOpener2.open(
cdr.nativeURL+filename,
'application/pdf',
//'text/plain',
{
error : function(e) {
alert('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success : function () {
}
}
);
};
function onFileSystemSuccessDelete(fileSystem) {
var entry="";
if (sessionStorage.platform.toLowerCase() == "android") {
entry=fileSystem;
}
else {
entry=fileSystem.root;
}
entry.getDirectory("Cordova/Sample_App", {create: true, exclusive: false}, onGetDirectorySuccessDelete, onGetDirectoryFail);
};
function onGetDirectorySuccessDelete(dir) {
dir.getFile(filename,{create: true, exclusive:false},gotFileEntryDelete, fail);
};
function gotFileEntryDelete(fileEntry) {
fileEntry.remove();
var uri = encodeURI("http://SERVER_IP:PORT/test.pdf");
fileTransfer.download(uri,cdr.nativeURL+filename,
function(entry) {
console.log("download complete: " + entry.toURL());
openFile();
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
alert("error");
},
true);
};
function fail(error){
alert("ec - " + error.code);
};
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = e.code;
break;
};
alert("Msg - " + msg);
};
function onGetDirectoryFail(error) {
alert("onGetDirectoryFail");
};
$('#delete').click(ClearDirectory);
function ClearDirectory() {
alert("delete");
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory,onFileSystemDirSuccess, fail);
}
else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,onFileSystemDirSuccess, fail);
}
}
function onFileSystemDirSuccess(fileSystem) {
var entry = "";
if (sessionStorage.platform.toLowerCase() == "android") {
entry=fileSystem;
}
else {
entry=fileSystem.root;
}
entry.getDirectory("Cordova",{create : true, exclusive : false},
function(entry) {
entry.removeRecursively(function() {
console.log("Remove Recursively Succeeded");
}, fail);
}, getDirFail);
}
function getDirFail(error){
alert("getDirFail - " + error.code);
};
}
I used:
<script>
$('a[href$=\\.pdf]').click(function() {
var myuri = this.href ;
alert(this.href);
/*alert just to make sure I got the right uri (which works fine)*/
cordova.plugins.fileOpener2.open(
'this.href', // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Download/starwars.pdf
'application/pdf',
{
error : function(e)
{
alert('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success : function ()
{
alert('file opened successfully');
}
}
);
return false;
});
</script>
and it hangs (i have the plugin declared in the config.xml file and present in the assets.
Can you pinpoint my error(s)?
Many thanks
Basically the issue is with the way you pass the file path paramter you pass to fileopener's open function and nothing wrong with the plugin as such.
If you pass this object inside single quote like 'this.href', it will be treated as a plain string and that's the issue. So you can use the approach as Joerg suggested in his answer.
Do check out this basic working sample app that demonstrates Cordova file operations. It should help you get started.
'this.href' is wrong, try it this way:
$('a[href$=\\.pdf]').click(function () {
var myuri = this.href;
alert(this.href);
/*alert just to make sure I got the right uri (which works fine)*/
cordova.plugins.fileOpener2.open(
myuri, // You can also use a Cordova-style file uri: cdvfile://localhost/persistent/Download/starwars.pdf
'application/pdf',
{
error: function (e) {
alert('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
alert('file opened successfully');
}
}
);
return false;
});
To sum up the answers for this complex problem:
first: fileopener2 will not work on its own, it needs other plugins to fit the purpose of opening pdf files on android. The other plugins needed are mentioned in Gandhi's excellent demo app available here.
Second: it is esssentiel to use Gandhi's app.js file that combines the different calls to plugins.
Third there are a number of functions involved in that file. In it the path is hard-coded, so everything seems to work well. But if you must use a dynamic path, then it must be stated globally (in other words, do not use "var" but simply myvar = this.href.
Although I found the last bits on my own, all the credit goes to Gandhi's excellent demo app which is a treasure trove for new plugin users he made available on github. +1 :-)
I have a function A() which calls function B(x, y); which again calls C(p,q);
A() --> B(x,y) -->C (p,q)
function A() {
B(x,y)
}
B() Processes JSONStore to extract data relevant for function C, Before JSONStore data extraction ends script makes a call for func C(p,q) so to avoid it I used setTimeOut with a 1 second delay.
function B(x,y) {
if(p===undefined || q===undefined) {
setTimeout(function() {
C(p,q);
}, 1000);
}
}
But I am getting error as Uncaught ReferenceError: method is not defined M979:192 C VM979:192 (anonymous function)
function C(p,q) {
.........
}
I have read many blogs related to setTimeOut and discovered this way to do it.
My code:
function Submit_Data() {
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
post("https://xyz/abc/StartChat.aspx", "post");
}
var regUserName,regUserMobile;
function post(path, method) {
method = method || "post"; // Set method to post by default if not specified.
var collectionName = 'Registration';
var JSONStoreCollections = {};
JSONStoreCollections[collectionName] = {};
JSONStoreCollections[collectionName].searchFields = {uName: 'string'};
WL.JSONStore.init(JSONStoreCollections)
.then(function () {
WL.JSONStore.get(collectionName).findAll().then(function (res) {
WL.Logger.info('Registration retrived is :', res);
console.log(JSON.stringify(res));
console.log(res[0].json.userName+" "+res[0].json.userMobile+" "+res[0].json.userPass+" "+res[0].json.userRePass);
regUserName=res[0].json.userName;
regUserMobile=res[0].json.userPass;
console.log("For Chat Data 1 is "+regUserName+" "+regUserMobile);
})
.fail(function (err) {
WL.Logger.error("Failed authentication "+err);
});
})
.fail(function (err) {
alert("Error is "+err);
});
if(regUserName===undefined || regUserMobile===undefined) {
setTimeout(function() {
openChat(regUserName,regUserName); // Error Here
}, 1000);
}
}
function openChat(regUserName,regUserName) {
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "chat");
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
var hiddenField3 = document.createElement("input");
console.log("For Chat Data 3 is "+regUserName+" "+regUserMobile);
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "vName");
hiddenField1.setAttribute("name", "vName");
hiddenField1.setAttribute("value", regUserName);
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "mobile");
hiddenField2.setAttribute("name", "21512");
hiddenField2.setAttribute("value", regUserMobile);
hiddenField3.setAttribute("type", "hidden");
hiddenField3.setAttribute("id", "state");
hiddenField3.setAttribute("name", "21524");
hiddenField3.setAttribute("value", "25");
document.body.appendChild(form);
form.submit();
}
These lines are illogically placed:
if(regUserName===undefined || regUserMobile===undefined) {
setTimeout(function() {
openChat(regUserName,regUserName); // Error Here
}, 1000);
}
Just call openChat in the JSONStore.get() callback:
regUserMobile=res[0].json.userPass;
console.log("For Chat Data 1 is "+regUserName+" "+regUserMobile);
if(regUserName===undefined || regUserMobile===undefined) {
openChat(regUserName,regUserName);
}
})
You also might want to replace === with !===, there. I would imagine that was intended to be a check to see if the parameters are filled.
I tried your code and i got the same error as you has mentioned, i have tweeked the code and now its working with this code just modify the URL link as per what you want.
function Submit_Data()
{
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("VodaFone Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
post("https://xyz/abc/StartChat.aspx", "post");
}
var regUserName,regUserMobile;
function post(path, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "chat");
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
var hiddenField3 = document.createElement("input");
var collectionName = 'Registration';
var JSONStoreCollections = {};
JSONStoreCollections[collectionName] = {};
JSONStoreCollections[collectionName].searchFields = {uName: 'string'};
WL.JSONStore.init(JSONStoreCollections)
.then(function ()
{
WL.JSONStore.get(collectionName).findAll().then(function (res)
{
WL.Logger.info('Registration retrived is :', res);
console.log(JSON.stringify(res));
console.log(res[0].json.userName+" "+res[0].json.userMobile+" "+res[0].json.userPass+" "+res[0].json.userRePass);
regUserName=res[0].json.userName;
regUserMobile=res[0].json.userMobile;
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "vName");
hiddenField1.setAttribute("name", "vName");
hiddenField1.setAttribute("value", regUserName);
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "mobile");
hiddenField2.setAttribute("name", "21512");
hiddenField2.setAttribute("value", regUserMobile);
hiddenField3.setAttribute("type", "hidden");
hiddenField3.setAttribute("id", "state");
hiddenField3.setAttribute("name", "21524");
hiddenField3.setAttribute("value", "25");
console.log("For Chat Data 1 is "+regUserName+" "+regUserMobile);
})
.fail(function (err)
{
WL.Logger.error("Failed authentication "+err);
});
})
.fail(function (err)
{
alert("Error is "+err);
});
if(regUserName===undefined || regUserMobile===undefined)
{
setTimeout(function() {
form.appendChild(hiddenField1);
form.appendChild(hiddenField2);
form.appendChild(hiddenField3);
document.body.appendChild(form);
form.submit();
}, 1000);
}
}
I know this is different way and probably not advicable but that is how i fixed it.
I tired this piece and its working correctly:
function A() {
B(1, 2)
}
function B(x,y) {
if(true) {
setTimeout(function() {
C(3,4);
}, 1000);
}
}
function C(p,q) {
alert('in c')
}
A()
The following code inside the tags gives error: "Object Expected".
<!-- JQuery/AJAX-->
<script type="text/javascript">
try {
$(document).ready(function(){
$("p").load(function(){
MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList');
});
});
}
catch(e)
{
alert(e.message);
}
</script>
The MakeRequest function resides in a separate .js file and I have included that file before the above given code.
Which object it is referring to?
Edited:
The MakeRequest function
function MakeRequest(DivName, ControlName, SqlQuery, ControlType)
{
var xmlHttp = getXMLHttp();
var strUrl = "";
if (ControlType = 'DropDown')
strUrl = "../phplibraries/filldropdown.php?DivName=" + DivName + "&DropDownControlName=" + ControlName + "&SqlQuery=" + SqlQuery;
else
strUrl = "../phplibraries/createelectioncategorymenu.php?DivName=" + DivName + "&ulName=" + ControlName + "&SqlQuery=" + SqlQuery;
alert(strUrl);
try
{
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText, DivName);
}
}
xmlHttp.open("GET", strUrl, true);
xmlHttp.send(null);
}
catch(err)
{
alert(err);
}
}
I know there is a big security issue above but please ignore it at this point of time.
You cannot call load() that way.
The first parameter of load takes a URL not a function. Perhaps you meant this:
$("p").load( MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList') );
That assumes that MakeRequest returns a formatted URL.
EDIT
.load() when used against a DOM element and the first parameter is a function, jQuery assumes you are attaching an event handler. However, p does not have a load event. If you want to wait for everything to load, try this (It doesn't have to be in DOM ready):
$(window).load( function(){
MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList')
});
MakeRequest rewrite
function MakeRequest(DivName, ControlName, SqlQuery, ControlType)
{
var strUrl = "", params = {};
if (ControlType = 'DropDown'){
strUrl = "../phplibraries/filldropdown.php";
params = {
DivName: DivName,
DropDownControlName: ControlName,
SqlQuery: SqlQuery
}
} else {
strUrl = "../phplibraries/createelectioncategorymenu.php";
params = {
DivName: DivName,
ulName: ControlName,
SqlQuery: SqlQuery
}
}
alert(strUrl);
$.get(strUrl, params, function(data){
HandleResponse(data, DivName);
});
}