Use a prepended image as wallpaper using Mozactivity Firefox OS - javascript

I want to fetch an image from the web and set it as wallpaper on the Firefox OS device.
So far I've tried two approaches,
$(document).on( 'click', '#share-image', function() {
walp = new Image()
walp.onload = function () {
var walCanvas = document.createElement('canvas');
walCanvas.width = walp.width;
walCanvas.height = walp.height;
var walCtx = walCanvas.getContext('2d');
walCtx.drawImage(walp,0,0);
walCanvas.toBlob( function (walBlob) {
var Activitiy = new MozActivity({
name: 'share',
data: {
type: 'image/*',
number: 1,
blobs: [walBlob]
}
});
});
};
walp.src = image; //image is the link to jpeg.
});
And this one...
var shareImage = document.querySelector("#share-image"),
imgToShare = document.querySelector('#prependedImage');
alert(imgToShare);
if (shareImage && imgToShare) {
shareImage.onclick = function () {
if(imgToShare.naturalWidth > 0) {
// Create dummy canvas
var blobCanvas = document.createElement("canvas");
blobCanvas.width = imgToShare.width;
blobCanvas.height = imgToShare.height;
// Get context and draw image
var blobCanvasContext = blobCanvas.getContext("2d");
blobCanvasContext.drawImage(imgToShare, 0, 0);
// Export to blob and share through a Web Activitiy
blobCanvas.toBlob(function (blob) {
new MozActivity({
name: "share",
data: {
type: "image/*",
number: 1,
blobs: [blob]
}
});
});
}
else {
alert("Image failed to load, can't be shared");
}
};
}
Both work for a locally saved image but don't work for the image that is fetched from a remote location.
I've also tried following approaches.
var pre = '<img width="100%" data-l10n-id="prependedImage" id="prependedImage" src="'+image+'" />';
$('#image1').prepend(pre);
and
$('#prependedImage').attr('src',image);
Both work, but neither presents the wallpaper menu unless it is a locally saved image.
I'm new to javascript and would appreciate an answer which explains what's wrong with code samples.
Thanks.

Can you try something like:
var xhr = new XMLHttpRequest({
mozSystem: true
});
xhr.open("GET", "http://25.media.tumblr.com/4751d1eccf9311ee0e05bdff819a7248/tumblr_n2yxzxzxr81rsg8blo1_250.png", true);
xhr.responseType = "blob";
xhr.onload = function () {
//sample activity
var activity = new MozActivity({
name: "share",
data: {
type: "image/*",
number:1,
blobs: [this.response],
filenames:["wallpapertest.png"]
},
});
};
xhr.onerror = function () {
alert("Error with System XHR");
};
xhr.send();
You will also need to set the app as privileged and add the systemxhr permission in the manifest:
"permissions": {
"systemXHR": {}
},
"type": "privileged"

Related

how to get file details of uploaded file in extJS

how to get file details of uploaded file in extJS
I am using file upload and I need to first conveert into Grid and then sumbit.
for grid conversion I have to take all files details like this :
File {
webkitRelativePath: "",
lastModifiedDate: Tue Jul 14 2009 11:02:31 GMT+0530 (India Standard Time),
name: "file.xlsx",
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
size: 780831
}
and here I am converting this to excell..
function handleFileSelect(evt){
var files = evt.target.files;
SessionConstant.uploadFileName = files[0].name;
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
// Next code
}
function ExcelToJSON () {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
var uploadata = [];
workbook.SheetNames.forEach(function(sheetName) {
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
uploadata.push(JSON.parse(json_object));
jQuery( '#xlx_json' ).val( json_object );
});
var uploadData = uploadata;
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
so this code when I am doing by using this
{
text:'Upload',
handler : function(){
var x = document.createElement("INPUT");
x.setAttribute("type", "file");
x.setAttribute("id","upload");
document.body.appendChild(x);
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
document.getElementById('upload').click();
},
}
This is working fine.
Now If I want to implement same thing fileupload in extJS so I can submit my form :
{
xtype: 'filefield',
cls:'common-fileupload',
itemId:'fileUploadId',
clearOnSubmit:false,
width:300,
labelWidth : '0',
name: 'myFile',
buttonConfig: {
text: 'Browse',
height : 30
},
listeners: {
change: function(fld, value) {
var newValue = value.replace(/C:\\fakepath\\/g, '');
fld.setRawValue(newValue);
this.up().submit({
url: 'url',
method: 'POST',
success: function (form, action) {
},
failure: function (form, action) {
},
error: function (form, action) {
}
});
}
},
style:'margin-right:10px'
}
So In Change method How to get files details so I can write my handleFileSelect method.
Any idea willbe helpfull.
For the classic framework, following way should work:
listeners: {
change: function(fld, value) {
let file = fld.fileInputEl.dom.files[0];
}
},

My IndexedDB add() in my service worker succeed but I cannot see the data it in the Chrome dev tools Application/Storage

I am on Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra,
I managed to get a service worker working, but I must say I am new at this.
I now try to get it to use an IndexedDB and store data in it.
It fetches data from a local web server in http and retrieve it without problem in json format.
The data format is :
[{"id":"1", "...":"...", ...},
{"id":"2", "...":"...", ...},
{"id":"3", "...":"...", ...},
...
{"id":"n", "...":"...", ...}]
it then adds the data to an IndexedDB without problem apparently because the onsuccess callback is triggered ...
entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}
But it does not appear in the Chrome dev tools!
Here is my service worker:
self.addEventListener('install',function(event)
{
event.waitUntil(
(new Promise(function(resolve,reject)resolve()}))
.then(function()
{return self.skipWaiting();}));
});
self.addEventListener('activate', function(event)
{
event.waitUntil(
(new Promise(function(resolve,reject){resolve()}))
.then(function() {return self.clients.claim();}));
});
self.addEventListener('message', function(event)
{
if(event.data.command=="data.load")
{
var options = event.data.options
var url = new URL(event.data.host+options.source);
var parameters = {entity:options.name,
options:encodeURIComponent(options.options)};
Object.keys(parameters)
.forEach(key => url.searchParams.append(key,
parameters[key]))
fetch(url).then(function(response)
{
if(response.ok)
{
response.json().then(function(data_json)
{
var entityData = data_json;
var request = indexedDB.open(options.name);
request.onerror = function(event)
{
console.log("indexedDB.open error :",event);
};
request.onsuccess = function(event)
{
console.log("indexedDB.open success :",event)
var db = event.target.result;
}
request.onupgradeneeded = function(event)
{
console.log("indexedDB.open upgrade :",event)
var db = event.target.result;
db.createObjectStore(options.options.id, { keyPath: "id" });
objectStore.transaction.oncomplete = function(event)
{
var entityObjectStore = db.transaction(options.options.id, "readwrite").objectStore(options.options.id);
for (var i in entityData)
{
var addRequest = entityObjectStore.add(entityData[i]);
addRequest.onerror = function(event)
{
console.log("entityObjectStore.add error :",event);
};
addRequest.onsuccess = function(event)
{
console.log("entityObjectStore.add success :",event);
};
}
}
};
});
}
});
}
else if(event.data.command=="data.get")
{
var command = event.data;
var request = indexedDB.open(command.domain);
request.onerror = function(event)
{
console.log("indexedDB.open error :",event);
};
request.onsuccess = function(event)
{
console.log("indexedDB.open success :", event)
var db = event.target.result;
var transaction = db.transaction([command.domain]);
var objectStore = transaction.objectStore(command.entity);
var request = objectStore.get(command.id);
request.onerror = function(event)
{
console.log("objectStore.get error :",event);
};
request.onsuccess = function(event)
{
console.log("objectStore.get success :",event);
console.log("request.result=" + request.result);
};
}
}
});
Here is the HTML file I use with it :
<!DOCTYPE html>
<html>
<head>
<title>My service worker app</title>
</head>
<body>
<button id="update">Update</button>
<div id="log"></div>
<script type="text/javascript">
function sendMessage(message)
{
return new Promise(function(resolve, reject)
{
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event)
{
if (event.data.error)
{
reject(event.data.error);
}
else
{
resolve(event.data);
}
};
});
}
if (navigator.serviceWorker.controller)
{
var url = navigator.serviceWorker.controller.scriptURL;
var initData = [
{
name:"my_entity_type",
source:"/webapp/data",
options:{id:"my_entity_type_id"}
}
]
for(var dataIndex in initData)
{
var data = initData[dataIndex]
sendMessage({
command:"data.load",
host: document.location.origin,
options: data
});
}
}
else
{
navigator.serviceWorker.register('/webapp/lt_sw.js')
.then(function(registration)
{
debug('Refresh to allow ServiceWorker to control this client', 'onload');
debug(registration.scope, 'register');
});
}
navigator.serviceWorker.addEventListener('controllerchange',
function()
{
var scriptURL = navigator.serviceWorker.controller.scriptURL;
debug(scriptURL, 'oncontrollerchange');
});
document.querySelector('#update').addEventListener('click',
function()
{
navigator.serviceWorker.ready.then(function(registration)
{
registration.update()
.then(function()
{
console.log('Checked for update');
})
.catch(function(error)
{
console.error('Update failed', error);
});
});
});
function debug(message, element)
{
var target = document.querySelector('#log');
console.log(element,":",message)
target.textContent = message;
}
</script>
</body>
</html>
Any idea about what I am, doing wrong?
Edit 1:
I modified the script in the html file so that update mechanism sends another message to the service worker asking for data :
document.querySelector('#update').addEventListener('click',
function()
{
navigator.serviceWorker.ready.then(function(registration)
{
registration.update()
.then(function()
{
console.log('Checked for update');
sendMessage({
command:"data.get",
domain:"database_name",
entity: "my_entity_type",
id: "my_entity_id"
});
})
.catch(function(error)
{
console.error('Update failed', error);
});
});
});
And I added the following line:
indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){ console.log("data.get all dbs:",sender.target.result); };
Just at the beginning of the data look up part:
else if(event.data.command=="data.get")
{
To list all the IndexedDBs on Chrome as explained here : https://stackoverflow.com/a/15234833/2360577
And I get all the databases I created previously!
data.get all dbs: DOMStringList {0: "db1", 1: "db2", 2: "db3", 3: "db4", length: 4}
Then I proceeded to list all ObjectStores in these dbs, also as explained in the previous link, by adding the following line :
indexedDB.open(<databaseName>).onsuccess = function(sender,args)
{"<databaseName>'s object stores",console.log(sender.target.result.objectStoreNames); };
And apart for one, where the data is processed and apparently does not work, they all had one object store with the same name as the db that contains it as expected ...
db1's object stores DOMStringList {0: "db1", length: 1}
db2's object stores DOMStringList {length: 0}
db3's object stores DOMStringList {0: "db3", length: 1}
db4's object stores DOMStringList {0: "db4", length: 1}
Then I had a look inside the object stores ...
indexedDB.open("db3").onsuccess = function(event)
{event.target.result.transaction(["db3"]).objectStore("db3")
.getAll().onsuccess = function(event)
{console.log("objectStore.getAll() success :",event.target.result)};};
And the entries are there as expected! But not in Application/Storage ...
Edit 2:
The error for db2 was apparently that I did not refresh the data in the database ... this part works now ...
Edit 3:
The answer was as simple as closing and reopening the dev tools ... like #wOxxOm suggested ...
It works for me if I close DevTools and open again. Did you try that?
You could also check the "Update on reload" button and try hard reset ctrl/shift+f5 to the same effect as #wOxxOm mentioned.

ExtJs minify Gets ignored

We have a CMS so I don't have access to the header of the HTML page which gets rendered for our extjs implementation. So I had to make a workaround which is like this:
Ext.local = {};
var lang = {
initLang: function (revisionNr) {
var local = localStorage.getItem('localLang')
if (!local) {
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
this.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
}
}
},
loadLangRemote: function (data) {
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
lang.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
},
loadLangLocal: function (data) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = 'js/freetext-deploy.min.js?rev={/literal}{$revisionNr}{literal}';
document.getElementsByTagName('head')[0].appendChild(jsElm);
Ext.Date.defaultFormat = 'd-m-Y';
if (!debug) {
Ext.Loader.config.disableCaching = true;
}
Ext.application({
name: 'freetextOrder',
appFolder: 'modules/extjs/freetextOrder/app',
controllers: [
'Main'
],
launch: function () {
var freetextOrder = Ext.create('Ext.container.Container', {
renderTo: Ext.get('freetextOrderDiv'),
layout: 'fit',
id: 'catalogAdministrationDiv_ext',
height: 800,
cls: 'x-dig-override',
items: [Ext.create('freetextOrder.view.base.MainView', {})],
layout:'fit'
});
}
});
Ext.local = data;
}
};
lang.initLang();
The problem I'm having is that the minified version gets ignored completely. I see it load on the http request but extjs ignores them.... even though I can see the objects are being created after include (via console log)
Anyone any idea how I can achieve this?
as i see none found the answer so i post my own here wich i came up with.
Since i could for the love of god not load the damn thing i refactored the loader and exported it into a Js. file. wich i reqired and called later on in code.
exported lang.js file:
Ext.define('Lang', {
singleton: true,
ApplicationConf: null,
Launch: function (launchConfig) {
this.ApplicationConf = launchConfig;
var local = localStorage.getItem('localLang');
var me = this;
this.loadLangRemote = function (data) {
debugger;
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
me.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
};
this.loadLangLocal = function (data) {
Ext.local = data;
Ext.lang = function (langId) {
if (Ext.local[langId]) {
return Ext.local[langId];
}
delete window.localStorage.localLang;
localStorage.setItem('localLangBackup', true);
return langId;
}
Ext.application(me.ApplicationConf);
};
if (!local) {
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
debugger;
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
debugger;
me.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
}
}
},
})
And IMPORTANT was to add the
Ext.onReady(function () {
Lang.Launch({
name: 'catalogAdministration',
appFold....
To the call of the Launch function in code, bacause it would have been not defined at run time. i added the file to the minified file first and call the Lang.Launch instead Ext.Application.
Hope somone has use of my solution :)

Script loaded with HeadJS runs only on second click

Script loaded with HeadJS runs only on second click. How to get Aviary launcher on first click?
http://jsfiddle.net/ynts/6hgEb/
function aviary(id, src) {
var $id = id;
var $src = src;
head.load(
"http://feather.aviary.com/js/feather.js",
function() {
var featherEditor = new Aviary.Feather({
apiKey: 12345,
apiVersion: 3
// ... ///
});
featherEditor.launch({
image: $id,
url: $src
});
}
);
}
$(document).on('click', 'img', function(){
var $img = $(this).attr('src');
aviary('edit-pic', $img);
});
You need to wait for the plugin to initialize, before calling the launch function. There is onLoad event you can use:
var featherEditor = new Aviary.Feather({
apiKey: 12345,
apiVersion: 3,
onLoad: function() {
featherEditor.launch({
image: $id,
url: $src
});
}
});
Answering mikebridge, for the case when it doesn`t open a second time:
Some dark reason prevents feather to be instantiated more than once.
Use window.globalAviaryFeather to hold the instance.
function launch(url) {
window.globalAviaryFeather.launch({
image: "imgId",
url: url
})
}
var url = "..."
if (window.globalAviaryFeather) {
launch(url)
} else {
window.globalAviaryFeather = new Aviary.Feather({
...
onLoad: function() {
self.launch(url)
}
})
}

How can I remove a whole IndexedDB database from JavaScript?

How can one remove a whole IndexedDB database from JavaScript, as opposed to just an object store? I'm using the IndexedDB shim, which may use WebSQL as its backend.
I'd mainly like to know how to do this for the PhantomJS (headless) browser, although Chrome, Safari (on iPad) and IE10 are other important browsers.
As far as I can tell, one should use indexedDB.deleteDatabase:
var req = indexedDB.deleteDatabase(databaseName);
req.onsuccess = function () {
console.log("Deleted database successfully");
};
req.onerror = function () {
console.log("Couldn't delete database");
};
req.onblocked = function () {
console.log("Couldn't delete database due to the operation being blocked");
};
I can confirm that it works with PhantomJS 1.9.0 and Chrome 26.0.1410.43.
I found that the following code works OK but to see the DB removed in the Chrome Resources Tab I have had to refresh the page.
Also I found I had problems with the Chrome debug tools running while doing transactions. Makes it harder to debug but if you close it while running code the code seems to work OK.
Significant also is to set a reference to the object store when opening the page.
Obviously the delete part of the code is in the deleteTheDB method.
Code derived from example provided by Craig Shoemaker on Pluralsight.
var IndDb = {
name: 'SiteVisitInsp',
version: 1000,
instance: {},
storenames: {
inspRecords: 'inspRecords',
images: 'images'
},
defaultErrorHandler: function (e) {
WriteOutText("Error found : " + e);
},
setDefaultErrorHandler: function (request) {
if ('onerror' in request) {
request.onerror = db.defaultErrorHandler;
}
if ('onblocked' in request) {
request.onblocked = db.defaultErrorHandler;
}
}
};
var dt = new Date();
var oneInspRecord =
{
recordId: 0,
dateCreated: dt,
dateOfInsp: dt,
weatherId: 0,
timeArrived: '',
timeDeparted: '',
projectId: 0,
contractorName: '',
DIWConsultant: '',
SiteForeman: '',
NoOfStaffOnSite: 0,
FileME: '',
ObservationNotes: '',
DiscussionNotes: '',
MachineryEquipment: '',
Materials: ''
};
var oneImage =
{
recordId: '',
imgSequence: 0,
imageStr: '',
dateCreated: dt
}
var SVInsp = {
nameOfDBStore: function () { alert("Indexed DB Store name : " + IndDb.name); },
createDB: function () {
openRequest = window.indexedDB.open(IndDb.name, IndDb.version);
openRequest.onupgradeneeded = function (e) {
var newVersion = e.target.result;
if (!newVersion.objectStoreNames.contains(IndDb.storenames.inspRecords)) {
newVersion.createObjectStore(IndDb.storenames.inspRecords,
{
autoIncrement: true
});
}
if (!newVersion.objectStoreNames.contains(IndDb.storenames.images)) {
newVersion.createObjectStore(IndDb.storenames.images,
{
autoIncrement: true
});
}
};
openRequest.onerror = openRequest.onblocked = 'Error'; //resultText;
openRequest.onsuccess = function (e) {
//WriteOutText("Database open");
IndDb.instance = e.target.result;
};
},
deleteTheDB: function () {
if (typeof IndDb.instance !== 'undefined') {
//WriteOutText("Closing the DB");
IndDb.instance.close();
var deleteRequest = indexedDB.deleteDatabase(IndDb.name)
deleteRequest.onblocked = function () {
console.log("Delete blocked.");
}
deleteRequest.onerror =
function () {
console.log("Error deleting the DB");
//alert("Error deleting the DB");
};
//"Error deleting the DB";
deleteRequest.onsuccess = function () {
console.log("Deleted OK.");
alert("*** NOTE : Requires page refresh to see the DB removed from the Resources IndexedDB tab in Chrome.");
//WriteOutText("Database deleted.");
};
};
}
}

Categories

Resources