While building my first mobile app using sencha touch 2 some questions got in my way and I can't seem to find their answer.
Where should an app configuration be stored (theme, language, font size ). I was thinking
to count the data from a store and if bigger than 0 work on that data otherwise add data( this would happen only the first time application is opened or localstorage cleared..). There are other options for this kind of thing(things like an array which will be changed when user is interacting with the app) ?
I need to use in my application around 100 images. I don't know what options I have here to embed the images into app. Saw lots of examples loading image from external server but not sure if there is an option for packing them with the app.
If I had an array with a name(key) and the image url(value), where should this array be ? in a json file and use an ajax load each time a need a name in there ?
Thanks.
Let me suggest few options:
1- App configuration : If app configuration is like set of constant values which won't change by user interaction you can create a file (e.g. properties.js) and load it on application load.
Properties = {
SERVICE_URL : 'http://mycompany.com/api',
PAGE_SIZE : 20
}
and to load it you just have to edit app.json
"js": [
{
"path": "touch/sencha-touch.js",
"x-bootstrap": true
},
{
"path": "resources/data/properties.js"
}
]
If you want to control these values then you can keep it on your server and give its URL as "path" in app.json
2- There is always option of packaging images with your app, just like all the icon & startup images are packaged but its not suggested because it increases size of your deployable and people with slow internet connections and low end devices might skip installing it if size it too large.
3- No need to load the JSON file every time you need it, you can cache the data in global variable after first load and keep referring to the array whenever required. Now where to define global variable is another interesting discussion with people suggesting lot of things but I prefer to have a singleton class which can keep all the global functions & variables. See this thread to understand how : Where do I put my global helper functions if they are needed before Ext.application() is being executed?
For Text we can Try like this
var A_address=Ext.getCmp('address').getValue(); //get the value
localStorage.setItem("Adult1_select1",A_select1); // assign localstore
var web_arrayTotalPAssengers=[];
web_arrayTotalPAssengers.push(localStorage.getItem("web_TotalPassengers"));
console.log(web_arrayTotalPAssengers);
// push the values in array...
Ext.Ajax.request({
url:'http:/...........',
method:'POST',
disableCaching: false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
jsonData: {
origin:Ext.decode(web_arrayTotalPAssengers), //decode and send
}
success:function(response)
{
console.log(response);
console.log("Success");
},
failure : function(response)
{
console.log("Failed");
}
Related
I am trying to play a video when developing locally with VueJS 2.
My code is the following :
<video class="back_video" :src="`../videos/Space${videoIndex}.mp4`" id="background-video"></video>
...
data :
function() {
return {
videoIndex:1
}
}
...
const vid = document.getElementById("background-video");
vid.crossOrigin = 'anonymous';
let playPromise = vid.play();
if (playPromise !== undefined) {
playPromise.then(function() {
console.log("video playing");
}).catch(function(error) {
console.error(error);
});
}
This code is causing the exception given in title. Tried in several browsers, always the same.
If I change the src by :
:src="require(`../videos/Space${videoIndex}.mp4`)"
it works.
But in that case building time is very long as I have many different videos in my videos directory, because adding require() will force to copy all videos in the running directory at build phase (vue-cli serve), and this is really annoying. In other words I want to refer videos that are outside the build directory to avoid this (but also to avoid having videos in my git).
It is interesting to note that when I deploy server side, it works perfectly with my original code
:src="`../videos/Space${videoIndex}.mp4`"
Note also that if i replace my code with simply
src="../videos/Space1.mp4"
it works too. So the video itself, or its location, are not the source of the problem.
Any clue ?
You can host your videos on a CDN to have something faster and easier to debug/work with.
Otherwise, it will need to bundle it locally and may take some time.
I use the dynamic source for vue-webpack images in nuxt :src="require('path/to/image' + dynamic.variable)" in my project navbar. If the users substitute their image through a form which refetches their information and deletes their previous image I get a webpack error module (img) not found (it does not find the new one): is there a way to solve this, like wait for webpack HRM to finish?
I tried setting up a setTimeout() of one second before user re-fetch and it works, but I don't like a random waiting, I'd use a promise or a sync dynamic, the point is webpack hot reload is not controlled by my functions.. I also tried with setting the dynamic path as a computed: but it doesn't fix.
My image tag:
<img v-if="this.$auth.user.image" class="userlogo m-2 rounded-circle" :src="require('#assets/images/users/' + this.$auth.user.image)" alt="usrimg">
My Useredit page methods:
...
methods: {
userEdit() {
//uploads the image
if (this.formImageFilename.name) {
let formImageData = new FormData()
formImageData.append('file', this.formImageFilename)
axios.post('/db/userimage', formImageData, { headers: { 'Content-Type': 'multipart/form-data' } })
// once it has uploaded the new image, it deletes the old one
.then(res=>{this.deleteOldImage()})
.catch(err=>{console.log(err)})
}else{
this.userUpdate() //if no new image has to be inserted, it proceeds to update the user information
}
},
deleteOldImage(){
if(this.$auth.user.image){axios.delete('/db/userimage', {data: {delimage: this.$auth.user.image}} )}
console.log(this.$auth.user.image + ' deleted')
this.userUpdate() // it has deleted the old image so it proceeds to update the user information
},
userUpdate(){
axios.put(
'/db/user', {
id: this.id,
name: this.formName,
surname: this.formSurname,
email: this.formEmail,
password: this.formPassword,
image: this.formImageFilename.name,
})
.then(() => { console.log('User updated'); this.userReload()}) // reloads the updated user information
.catch(err => {console.log(err)} )
},
userReload(){
console.log('User reloading..')
this.$auth.fetchUser()
.then(() => { console.log('User reloaded')})
.catch(err => {console.log(err)} )
},
}
...
the problem happens after "console.log('User reloading..')" and before "console.log('User reloaded');", it is not related to the file upload nor the server response. I broke a single function in many little ones just to check the function progression and its asynchronous dynamics but the only one that is not manageable is the webpack hot reload :/
I'd like the users to upload their images and see their logo in the Navbar appear updated after submitting the form.
First of all, as somebody told you in the comments, webpack hmr shouldn't be used for production.
In Nuxt, everything that you reference from the assets folder will be optimized and bundled into the project package. So the ideal use case for this folder is all assets that can be packaged and optimized, and most likely won't change like fonts, css, background images, icons, etc.
Then, require is called only once by webpack when it is either building the site for local development or building the site for generating a production package. The problem in your case is that you delete the original file while you're in development and webpack tries to read it and fails.
In the case of these images that the user uploads, I think you should use the static folder instead and instead of using require you'll have to change the :src with
:src="'/images/users/' + this.$auth.user.image"
Let me know if this helps.
Okay, I probably solved it.
HMR: you are of course right. Thank you for pointing out, I am sorry, I am a beginner and I try to understand stuff along the way.
Aldarund, thank you, your idea of not changing the path and cache it client side.. I am too noob to understand how I could implement it ( :) ) but it gave me a good hint: the solution was to keep the image name as the user id + the '.png' extension and to manage the image with jimp so that the image name, extension and file type are always the same, and with or without webpack compiling the new path, I always have the correct require().
Jair, thank you for the help, I didn't follow that road, but I will keep it as a second chance if my way creates errors. Just to be specific: the error comes when it does not find -and asks for the name of- the NEW image, not the OLD one, as I wrote in my question: it happens because the fetchUser() functions reloads the user information including the new image name.
Do you guys see any future problems in my methodology?
Really thank you for your answers. I am learning alone and it's great to receive support.
I'm trying to automate an application that uses form security in order to upload a file and then scrape data from the returned HTML.
I started out using the solution from this question. I can define my steps and get through the entire workflow as long as the last step is rendering the page.
Here are the two steps that are the meat of my script:
function() {
page.open("https://remotesite.com/do/something", function(status) {
if ('success' === status) {
page.uploadFile('input[name=file]', 'x.csv');
page.evaluate(function() {
// assignButton is used to associate modules with an account
document.getElementById("assignButton").click();
});
}
});
},
function() {
page.render('upload-results.png');
page.evaluate(function() {
var results = document.getElementById("moduleProcessingReport");
console.log("results: " + results);
});
},
When I run the script, I see that the output render is correct. However, the evaluate part isn't working. I can confirm that my DOM selection is correct by running it in the Javascript console while on the remote site.
I have seen other questions, but they revolve around using setTimeout. Unfortunately, the step strategy from the original approach already has a timeout.
UPDATE
I tried a slightly different approach, using this post and got similar results. I believe that document uses an older PhantomJS API, so I used the 'onLoadFinished' event to drive between steps.
i recomend you use casperjs or if you use PJS's webPage.injectScript() you could load up jquery and then your own script to do form input/navigation.
I'm building a Safari extension with two different content scripts. One script needs to be injected into all http pages (but not https pages). The other one only gets injected into google.com pages regardless of scheme.
In order to achieve this, I have set Extension Website Access to:
This should mean that at a high level, content scripts in my extension should be able to access all pages.
To get more fine-grained control, I then programatically inject the content scripts into URLs which match my patterns.
App = {
content: {
// Inject into unsecure pages.
whitelist: ['http://*/*'],
// But not into secure pages.
blackList: ['https://*/*'],
loc: safari.extension.baseURI + 'data/content.js'
},
results: {
// Inject this script into all google.com pages
whiteList: ['http://*.google.com/*', 'https://*.google.com/*'],
// Surely I don't need a blacklist if I specify a whitelist?
blacklist: undefined,
loc: safari.extension.baseURI + 'data/results.js',
}
};
// Inject the first content script.
safari.extension.addContentScriptFromURL(App.content.loc,
App.content.whitelist, App.content.blacklist, false);
// Inject the second content script.
safari.extension.addContentStyleSheetFromURL(App.results.cssLoc,
App.results.whitelist, App.results.blacklist, false);
The problem is that both scripts are being injected into all pages. It's as if my white and blacklists do nothing. What am I doing wrong?
I was using capitals in my whilelist/blacklist definitions at the top:
App = {
content: {
blackList: ['https://*/*'],
},
results: {
whiteList: ['http://*.google.com/*', 'https://*.google.com/*']
}
};
But then using non-capitalized versions of the variables when I pass the lists into the script injection function.
safari.extension.addContentScriptFromURL(App.content.loc, App.content.whitelist, App.content.blacklist, false);
This obviously means that undefined was being passed into the injection function rather than an actual whitelist/blacklist.
I've been able to send data from the background page to the content script. but this is done using sendrequest(). I will need to send data back and forth so I'm trying to figure out the correct syntax for using the port.postmessage from background page to content script. I have already read, several times, the google page on Messaging and I don't seem to get it. I even copied the code directly from the page and tested with no result. All I'm trying to do for now is send data from background page to content script using connect as opposed to sendrequest. The response from the content script I will deal with later as code with this response has been the main thorn. I just want to understand the process one step at a time without the extra knowledge of sending a response back.
I'm not sure if this contravenes the rules of this board but can someone PLEASE give me an example of some code to do this (background page and content script excerpt, the background page is the sender).
I've asked for assistance several times on this site only to be told to read the documentation or check out sites I've already visited.
If you just want any example of opening a port from the extension to a content script, here's the simplest I can think of. The background just opens a port and sends "Hello tab!" over the port, and the content script sends a message to the background any time you click on the webpage.
I think this is pretty simple, so I don't know why you are so stressed. Just make sure that the content tab is already listening when the background tries to connect (I do this by waiting until the "complete" event).
manifest.json:
{
"name": "TestExt",
"version": "0.1",
"background_page": "background.html",
"content_scripts": [{
"matches": ["http://localhost/*"], // same as background.html regexp
"js": ["injected.js"]
}],
"permissions": [
"tabs" // ability to inject js and listen to onUpdated
]
}
background.html:
<script>
var interestingTabs = {};
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// same as manifest.json wildcard
if (changeInfo.url && /http:\/\/localhost(:\d+)?\/(.|$)/.test(changeInfo.url)) {
interestingTabs[tabId] = true;
}
if (changeInfo.status === 'complete' && interestingTabs[tabId]) {
delete interestingTabs[tabId];
console.log('Trying to connect to tab ' + tabId);
var port = chrome.tabs.connect(tabId);
port.onMessage.addListener(function(m) {
console.log('received message from tab ' + tabId + ':');
console.log(m);
});
port.postMessage('Hello tab!');
}
});
</script>
injection.js:
chrome.extension.onConnect.addListener(function(port) {
console.log('Connected to content script!');
port.onMessage.addListener(function(m) {
console.log('Received message:');
console.log(m);
});
document.documentElement.addEventListener('click', function(e) {
port.postMessage('User clicked on a ' + e.target.tagName);
}, true);
});
Detailed documentation and easy (the most basic) examples shown in the documentation page.
Plus, a quick search in stackoverflow will allow you to see many similar questions with detailed answers.