chrome extension download files - javascript

I'm writing a js extension for chrome that should download multiple created files.
the problem is that chrome auto opens the file in the current tab at the following address:
filesystem:https://stackoverflow.com//temporary/myfile.ini
and second if I cycle on an array made this way
fileini = [ ["filename",file-content], [], ... ] it just print the last one
and if I try to cycle on it using a setTimeout I get an error from the console
below I post the code
function createDataFile(filename, content) {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 1024 * 1024 * 20, function(fs) {
fs.root.getFile(filename, {
create : true
}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob(content);
console.log("5");
fileWriter.addEventListener("writeend", function() {
// navigate to file, will download
location.href = fileEntry.toURL();
}, false);
fileWriter.write(blob);
}, function() {
});
}, function() {
});
}, errorHandler);
}
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 = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
}
createFileCycle();
function prnt(x) {
var y;
if (fileini[x] !== undefined) {
createDataFile(fileini[x][0], objToArray(fileini[x][1]));
y = x - 1;
console.log("printed file" + x);
} else {
y = x - 1;
}
if (x > 0)
return setTimeout(function() {
console.log("going to print file " + y);
prnt(y);
}, 500);
else
return 0;
}
prnt(fileini.length - 1);
}
function createFileCycle() creates fileini array as explained above
I hope someone could help me.
btw months ago on an old notebook running ubuntu 32bit I had it working, now on windows 7 it doesn't work and I cannot get around the problem.

Related

Getting NotAllowedError: play() failed because the user didn't interact with the document first even though user is keypressing

First, this code was working for 6 months before it started erroring so I'm trying to figure out what has gone wrong despite the code staying the same. I'm getting the error:
Uncaught (in promise) NotAllowedError: play() failed because the user
didn't interact with the document first.
at https://player.vimeo.com/api/player.js:2:8680
at Array.forEach ()
at b (https://player.vimeo.com/api/player.js:2:8654)
at e (https://player.vimeo.com/api/player.js:2:10401)
when a user presses a key to play a video. I used the Vimeo Player API. Code looks like:
<script src="https://player.vimeo.com/api/player.js"></script>
<script>
window.addEventListener("keypress", (e) => {
var iframe = document.querySelector('iframe');
var embedOptions = {
autoplay: true,
muted: true
};
iframe.allow = "autoplay";
iframe.autoplay = "";
var iframePlayer = new Vimeo.Player(iframe, embedOptions);
iframe.style.zIndex = 0;
let key = e.key;
let URL;
const overlay = document.getElementById("header");
const logo = document.getElementsByTagName("img")[0];
const subtitle = document.getElementsByTagName("h3")[0];
function startVideo () {
overlay.style.opacity = 0;
logo.style.opacity = 0;
subtitle.style.opacity = 0;
subtitle.style.visibility = 'hidden';
}
function endVideo () {
overlay.style.opacity = 1;
logo.style.opacity = 1;
subtitle.style.opacity = 1;
subtitle.style.visibility = 'visible';
}
switch (key) {
case "a":
case "A":
case " ":
URL = "290178807";
break;
case "b":
case "B":
case "]":
case "}":
URL = "290179039";
break;
}
iframePlayer.loadVideo(URL).then(function(id) {
// the video successfully loaded
console.log(e.key, URL, iframe);
iframePlayer.play().then(function() {
startVideo();
iframePlayer.on('ended', function() {
endVideo();
})
});
}).catch(function(error) {
switch (error.name) {
case 'TypeError':
// the id was not a number
break;
case 'PasswordError':
// the video is password-protected and the viewer needs to enter the
// password first
break;
case 'PrivacyError':
// the video is password-protected or private
break;
default:
// some other error occurred
break;
}
});
})
</script>
I removed the huge switch statement that determines which video to play but that section was just a continuation of what the switch statement left in.
I added the embedOptions hoping that I could at least get it back to working though muted but even that doesn't seem to work. Adding iframe.muted = "muted" also proved fruitless. Also might be worth noting that this is a custom Squarespace although I don't think it's related as it was working before with the same code.
It seems that you can't set the allow="autoplay" attribute dynamically.
It should be on the iframe before the event handler is executed. Also iframe.autoplay is not a valid property I think.
I would also add this chunk of code before/out of the event handler.
var iframe = document.querySelector('iframe');
var embedOptions = {
autoplay: true,
muted: true
};
// iframe.allow = "autoplay";
// iframe.autoplay = "";
var iframePlayer = new Vimeo.Player(iframe, embedOptions);
iframe.style.zIndex = 0;
This is working code.
<iframe allow="autoplay" src="https://player.vimeo.com/video/76979871" frameborder="0"></iframe>
<script src="https://player.vimeo.com/api/player.js"></script>
<script>
var iframe = document.querySelector('iframe');
var embedOptions = {
autoplay: true,
muted: true
};
// iframe.allow = "autoplay";
// iframe.autoplay = "";
var iframePlayer = new Vimeo.Player(iframe, embedOptions);
iframe.style.zIndex = 0;
window.addEventListener("keypress", (e) => {
let key = e.key;
let URL;
const overlay = document.getElementById("header");
const logo = document.getElementsByTagName("img")[0];
const subtitle = document.getElementsByTagName("h3")[0];
function startVideo () {
overlay.style.opacity = 0;
logo.style.opacity = 0;
subtitle.style.opacity = 0;
subtitle.style.visibility = 'hidden';
}
function endVideo () {
overlay.style.opacity = 1;
logo.style.opacity = 1;
subtitle.style.opacity = 1;
subtitle.style.visibility = 'visible';
}
switch (key) {
case "a":
case "A":
case " ":
URL = "290178807";
break;
case "b":
case "B":
case "]":
case "}":
URL = "290179039";
break;
}
iframePlayer.loadVideo(URL).then(function(id) {
// the video successfully loaded
console.log(e.key, URL, iframe);
iframePlayer.play().then(function() {
startVideo();
iframePlayer.on('ended', function() {
endVideo();
})
});
}).catch(function(error) {
switch (error.name) {
case 'TypeError':
// the id was not a number
break;
case 'PasswordError':
// the video is password-protected and the viewer needs to enter the
// password first
break;
case 'PrivacyError':
// the video is password-protected or private
break;
default:
// some other error occurred
break;
}
});
})
</script>

how to append to file with cordova-plugin-file

I'm trying to append text to a file.
I have followed tutorial of Html5rocks as suggested by plugins's github page.
I've sucessfully created a file and wrote to it. But when im trying to append text, i got a write success event but no text is added. I'm only able to change characters but no characted added to the end. It's not an async issue, i'm also trying live test with chrome's js console. Im also using fileWriter.seek(fileWriter.length) before trying to write at the end. (but seek(0) to write a the beginning)
there is the module i wrote :
'use strict';
function File_mgmt(name) {
var name = name;
var myfile = '';
var next_write = '';
var that = this;
var errorHandler = function (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 = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
};
var init = function() {
console.log("init");
request(gotFS);
};
var gotFS = function() {
console.log("gotfs");
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
dir.getFile(name, {create:true}, function(file) {
myfile = file;
}, errorHandler);
});
};
this.write = function (data) {
myfile.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
fileWriter.seek(fileWriter.length);
fileWriter.write(data);
}, errorHandler);
};
this.reopen = function() {
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
dir.getFile(name, {create:false}, function(file) {
myfile = file;
}, errorHandler);
});
};
this.getfile = function() {
return myfile;
};
this.writeTextBlob = function(data) {
this.write(new Blob([data], {type: 'text/plain'}));
};
var request = function(success){
var fail = function() {console.log("failed to initialise system")};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024*1024, success, fail);
};
var writer = function() {
myfile.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
fileWriter.seek(fileWriter.length);
fileWriter.write(next_write);
}, errorHandler);
};
this.testWrite = function(data) {
next_write = data;
request(writer);
};
init();
return this;
}
I'm using it with chrome console with
var f = new File_mgmt("test");
f.writeTextBlob("test1");
f.writeTextBlob("test2");
Edit
I've tried to pass by a window.requestFileSystem() to append but it still doesnt work, I've also updated my code.
now i'm doing
var f = new File_mgmt("test");
f.testWrite("test1");
f.testWrite("test2");
It's appearing than my file actually got new data. I had to unplugged then replugged usb cable to see the new data appened to my file.
May be it's a problem with Windows. I'll look if i got the same problem on linux.

bulkTransfer "Transfer failed."

I'm not getting any kind of transfer to happen between my chrome app and a simple device just waiting for data to come in on its uart rx line. The device's interface's endpoint's type is bulk, although I've tried every transfer type available (control, bulk, isochronous, and interrupt). Examples from here. I've also tried claiming the device, but that does not seem to be applicable if using findDevices and fails as well.
I'm assuming that by finding the device, I know that it has been discovered, permissions are OK and that it has been opened OK.
I'm using a UART-to-USB adapter on a mac. I've spoken to the same hardware setup using pysusb and a python script, so I know it can be done.
var DEVICE_INFO = {"vendorId": 1027, "productId": 24577};
var searchForUsbDevice = function() {
chrome.usb.findDevices(DEVICE_INFO, onDeviceFound);
}
var onDeviceFound = function(devices) {
if (devices) {
if (0 < devices.length) {
if (1 === devices.length) {
device_ = devices[0];
console.log("Device found. And opened?");
getInterfaces();
getConfiguration();
//claimDevice();
investigateDevice();
} else {
console.log("Ensure one and ONLY ONE device is plugged in.");
}
} else {
console.log("Device could not be found");
setTimeout(searchForUsbDevice, 1000);
}
} else {
console.log("Permission denied.");
}
};
var investigateDevice = function() {
testBulkTransfer();
//testIsochronousTransfer();
//testInterruptTransfer();
//testControlTransfer();
setTimeout(investigateDevice, 1000);
};
var testBulkTransfer = function() {
var transferInfo = {
"direction": "out",
"endpoint": 1,
"data": new Uint8Array([32, 2, 1, 2]).buffer
};
chrome.usb.bulkTransfer(device_, transferInfo, function(info) {
if (chrome.runtime.lastError) {
console.log("info: " + JSON.stringify(info));
console.log("runtime error: " + JSON.stringify(chrome.runtime.lastError.message));
return;
}
console.log("transfer result: " + ((0 === info.resultCode) ? "succeeded" : "failed"));
});
};
var getConfiguration = function() {
chrome.usb.getConfiguration(device_, function(config) {
if (chrome.runtime.lastError) {
console.log("runtime error: " + JSON.stringify(chrome.runtime.lastError.message));
return;
}
console.log("config: ");
console.log(config);
});
};
var getInterfaces = function() {
chrome.usb.listInterfaces(device_, function(descriptors) {
if (chrome.runtime.lastError) {
console.log("runtime error: " + JSON.stringify(chrome.runtime.lastError.message));
return;
}
console.log("descriptors: ");
console.log(descriptors);
});
};
The appropriate API for that UART-to-USB adapter is chrome.serial, NOT chrome.usb.
https://developer.chrome.com/apps/app_serial

Downloading files stuck android application: worklight

i implemented a application on work-light in which I need to download files from the server, its works well on Iphone5 means files are downloading smoothly without stuck the application flow.however when i run the application on my Samsung galaxy s2 (V 4.1) and start downloading files using for loop my application get stuck till the downloading completed. however its works fine when i have only one file to dowload but when the count is above 3 or 4 application get stuck.
if(networkInfo.networkConnectionType=='WIFI'){
$(brandClassDis).addClass('ui-disabled'); // Disabling the Brand.
$(".lms_loadernew").css("display", "block");
var syncProgBar = "#syncProgressBar"+result[0].json.BrandID;
var syncProgLabel = "#syncLoadingLabel"+result[0].json.BrandID;
$(syncProgBar).progressbar({
value: 0,
}).show();
$(syncProgLabel).text(parseInt(0, 10)+"%").show();
localStorage.setItem("download"+result[0].json.BrandID,0);
localStorage.setItem("downloadSucc"+result[0].json.BrandID,0);
for(var i=0; i<result.length; i++){
var obj = {VideoID:result[i].json.VideoID,BrandID:result[i].json.BrandID,CourseID:result[i].json.CourseID,LoadingStatus:"0"};
VideosList.add(obj,{push:false});
result[i].json.IsDownload = 2;
Videos.replace(result);
**downloadFolder(result[i],result.length)**
}
}
function downloadFolder(result,numVideoBrand){
try{
var loaderPer = 0;
var courseId ="#sync_"+result.json.CourseID.replace(/ /g,'');
var courseLabelId ="#loadingLabel"+result.json.CourseID.replace(/ /g,'');
var syncProgBar = "#syncProgressBar"+result.json.BrandID.replace(/ /g,'');
var syncProgLabel = "#syncLoadingLabel"+result.json.BrandID.replace(/ /g,'');
var serverLoc = encodeURI(result.json.DownloadName);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getDirectory("LMS_APP", {create: true, exclusive: false}, function(directory){
var localPath = directory.fullPath+"/"+"Videos"+"/"+zipFileName;
var ft = new FileTransfer();
ft.download(serverLoc,localPath, function(entry) {
entry.file(function(file) {
WL.Logger.debug("File size: " + file.size);
if(file.size<=854){
downloadFail("",result,numVideoBrand);
entry.remove(successRemove, failRemove);
}else{
if(localStorage.getItem("download"+result.json.BrandID) == null || localStorage.getItem("download"+result.json.BrandID) =="" || localStorage.getItem("download"+result.json.BrandID) == undefined){
localStorage.setItem("download"+result.json.BrandID,1);
}else{
localStorage.setItem("download"+result.json.BrandID,(localStorage.getItem("download"+result.json.BrandID)-(-1)));
}
localStorage.setItem("downloadSucc"+result.json.BrandID,(localStorage.getItem("downloadSucc"+result.json.BrandID)-(-1)));
WL.Logger.debug("Folder is:---->"+directory.fullPath+"/"+zipFileName);
WL.Logger.debug("download"+localStorage.getItem("download"+result.json.BrandID)+"..."+numVideoBrand+"........"+ localStorage.getItem("downloadSucc"+result.json.BrandID));
var loadedVideoPer = (( localStorage.getItem("download"+result.json.BrandID)/numVideoBrand)* 100);
$(syncProgBar).progressbar({
value: loadedVideoPer,
});
$(syncProgLabel).text(parseInt(loadedVideoPer, 10)+"%");
$(courseId).hide();
$(courseLabelId).hide();
}
}, function(error){downloadFail(error,result,numVideoBrand);});
}, function(error) {
});
$(courseId).progressbar({
value: loaderPer,
}).show();
$(courseLabelId).text(parseInt(loaderPer, 10)+"%").show();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
loaderPer = ((progressEvent.loaded / progressEvent.total)*100);
$(courseId).progressbar({
value: loaderPer,
});
$(courseLabelId).text(parseInt(loaderPer, 10)+"%");
//courseLabelId.text(parseInt(loaderPer, 10) + "%" );
loadingStatus(result);
}
};
},function(error){
downloadFail(error,result,numVideoBrand);
});
}, function(error){
downloadFail(error,result,numVideoBrand);
});
}catch(e){
WL.Logger.debug("exp in downloadFile: "+e);
//alert("exp "+videoLoader);
}
}
From the comments, the solution was to:
download file in queue, coz downloading all file at once cause the
application stuck...

QUOTA_EXCEEDED_ERR in Chrome FileSystem API

In Chrome23/Mac OS 10.8.2 this fiddle logs an error, and I want to know why.
Surprisingly enough, error does not occur if I put a breakpoint on the line that says '// BREAKPOINT' and simply resume execution.
Is it possible for JS to exceed some call rate limit in Chrome? I couldn't think of a better explanation.
Full code (I am using lodash, see its documentation of _.bind and _.bindAll):
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.LocalFileSystem = window.LocalFileSystem || {PERSISTENT: window.PERSISTENT};
fs = {
initFS: function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT,
1024 * 1024, this.gotFS, this.fail);
},
fail: function(source, err) {
err.source = source;
var msg = '';
switch (err.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 = 'Unknown Error';
break;
};
err.msg = msg;
console.log('err ', JSON.stringify(err));
},
failarg: function(msg) {
return _.bind(this.fail, this, msg);
},
gotFS: function(fs) {
this.fs = this.fs || fs;
this.readConfig();
this.listApps(fs.root); // BREAKPOINT
},
listApps: function(fsroot) {
this.rootReader = this.rootReader || fsroot.createReader();
this.rootReader.readEntries(this.gotRootEntries, this.fail);
},
gotRootEntries: function(entries) {
_(entries).forEach(function(entry) {
if (entry.isDirectory && this.controller) {
// TODO
}
});
},
readConfig: function() {
this.fs.root.getFile('config.json', {create:true}, this.gotConfigFileEntry, this.failarg('getFile'));
},
gotConfigFileEntry: function(entry) {
entry.file(this.gotConfigFile, this.failarg('entry.file'));
},
gotConfigFile: function(file) {
this.configFile = file;
var reader = new FileReader();
reader.onloaded = function(evt) {
if (evt.target.result) {
this.config = JSON.parse(evt.target.result);
}
};
reader.readAsText(this.configFile);
},
};
_.bindAll(fs);
$(function() {
fs.initFS();
});​
The following Fiddle, based on the original HTML 5 Rocks article (http://www.html5rocks.com/en/tutorials/file/filesystem/), demonstrates how to invoke the quota system.
http://jsfiddle.net/kim3er/h76qq/1/
window.webkitStorageInfo.requestQuota(PERSISTENT, 1024*1024, function(grantedBytes) {
//window.requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
initFS(grantedBytes);
}, function(e) {
console.log('Error', e);
});

Categories

Resources