How to setInterval correct in casperjs? - javascript

I try to use webserver talk to outside world and setInterval want its execution automatically every sometimes.
One of my casperjs setting is this.capture(x + 'apple.png');
I though it will show three images under my folder if setInterval run three times.
As the result i only save one image is 1apple.png.
Although i can see a lots of info on my terminal
I want to ask what step should i miss it ? Any help would be appreciated.
Thanks in advance.
Here is my code today.js:
var webserver = require('webserver');
var server = webserver.create();
var service = server.listen('8080', {
'keepAlive': true
}, function (request, response) {
response.statusCode = 200;
response.write('<html><body>What the hell~~</body></html>');
var casper = require("casper").create({
verbose: true,
logLevel: 'debug', // debug, info, warning, error
pageSettings: {
loadImages: false,
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
}
});
var movieTitle = [];
var movieEnTitle = [];
var title = [];
var movieTime = [];
var movieVersion = [];
var city = '台南';
var latitude = 22.993089;
var longitude = 120.196876;
var theaterName = '今日戲院';
var data = {};
data.theater = [];
data.movie = [];
var x =1;
function getMovieTitle() {
var title = document.querySelectorAll('div.theaterlist_name a');
return Array.prototype.map.call(title, function (e) {
return e.innerText;
});
};
function getEnTitle() {
var title = document.querySelectorAll('div.en a');
return Array.prototype.map.call(title, function (e) {
return e.innerText;
});
};
function getMovieTime() {
var title = document.querySelectorAll('ul.theater_time');
return Array.prototype.map.call(title, function (e) {
return e.innerText;
});
};
function getMovieVersion() {
var version = document.querySelectorAll('div.tapR');
return Array.prototype.map.call(version, function (e) {
return e.innerText;
});
};
// 台南 今日戲院 from 奇摩
casper.start('https://tw.movies.yahoo.com/theater_result.html/id=67', function () {
this.echo(this.getTitle());
});
casper.then(function () {
this.echo('Image');
this.echo(x);
this.capture(x + 'apple.png');
x++;
});
casper.then(function () {
movieTitle = this.evaluate(getMovieTitle);
movieEnTitle = this.evaluate(getEnTitle);
movieTime = this.evaluate(getMovieTime);
movieVersion = this.evaluate(getMovieVersion);
});
casper.then(function () {
console.log('Print:\n');
this.echo(movieTitle.length + ' Movie title found :\n');
this.echo(movieTitle.join('\n'));
this.echo(movieEnTitle.length + ' Movie title found :\n');
this.echo(movieEnTitle.join('\n'));
this.echo(movieTime.length + ' Movie time found :\n');
this.echo(movieTime.join('\n'));
this.echo(movieVersion.length + ' Movie version found :\n');
this.echo(movieVersion.join('\n'));
this.echo(outPutJSON());
});
function outPutJSON() {
data.theater.push({
name: theaterName,
city: city,
latitude: latitude,
longitude: longitude
});
// 將中英文名字合併
for (var i = 0; i < movieTitle.length; i++) {
title.push(movieTitle[i] + movieEnTitle[i]);
}
for (var i = 0; i < movieTime.length; i++) {
var name = title[i];
var sourceTime = movieTime[i].match(/.{1,5}/g);
var times = [];
times.push(sourceTime);
var version = movieVersion[i];
data.movie.push({
name: name,
version: version,
time: times
});
}
return JSON.stringify(data);
}
// casper.run(function () {
// // this.echo('Done').exit();
// this.echo('Done');
// });
setInterval(function () {
casper.run(function () {
// this.echo('Done').exit();
this.echo('Done');
});
}, 2000);
response.write(outPutJSON());
response.close();
});
Here is my folder when i command this file , you can see only capture image once 1apple.png.

One way to achieve what you want would be have a cron job scrape the site at the desired frequency and put the results in a directory served by a web server. Below is a stand-alone script that will fetch the title and capture the image of a site once per hour. Modifying this.step is probably unwise (inspiration from this site:
https://github.com/yotsumoto/casperjs-goto )
var casper = require('casper').create();
var x = 0;
casper.start('http://localhost:8080', function() {
// change 'http://localhost:8080' to the site to be scraped
this.echo(this.getTitle());
this.capture(x++ + '.png');
this.wait(60 * 60 * 1000, function() {
// 60 minutes * 60 seconds * 1000 milliseconds
this.step = 0;
});
});
casper.run();

Related

how to pause and resume voice recording in android using cordova media plugin

I'm using angularjs in visual studio.using cordova media plugin startRecord() and stopRecord() is working but not able to pause and resume recording.I'm not using media capture plugin as i don't have default recorder installed.
This is my code:
var audurl = '///storage/emulated/0/New/';
audurl += 'Voice_' + '.amr';
var mediaRec;
function recordAudio() {
mediaRec = new Media(audurl, onSuccess, onError);
mediaRec.startRecord();
}
function pauseAudio() {
mediaRec = new Media(audurl, onSuccess, onError);
mediaRec.pauseRecord();
}
thanks...
On my phone the method media.resumeRecord was not available, although in this soure-code it is defined. Nevertheless you can take advantage of all other methods, like startRecord and stopRecord, to rebuild a kind of resumeRecord function, as it is done in a handler below:
var myRecordHandler = function () {
// ALL RECORDED FILES ARE SAVED IN THIS ARRAY
var recordedAudioFiles = [];
// REMEMBER POSITION WHEN PLAYING IS STOPPED
var currentPosition = {index:0,shift:0};
// PAUSE-MODE
var paused = false;
// SET A SPECIFC DIRECTORY WHERE THE FILES ARE STORED INTO
// DEFAULT: ''
this.setDirectory = function(dir) {this.dir=dir;};
// SET FILENAME
// DEFAULT: recoredFilesX
this.setFilename = function(filename) {this.filename=filename;};
// SET MIME/Type of THE FILES;
// DEFAULT: mp3
this.setFileType = function(type) {this.filetype=type;};
// GET ALL RECORED FILES
this.getAllFiles = function() {return recordedAudioFiles;};
// STOP/PAUSE RECORDED FILES
var handleRecordedFileHold = function () {
for (var r = 0; r < recordedAudioFiles.length; r++) {
var recordedAudioFile = recordedAudioFiles[r];
if(recordedAudioFile.isBeingRecorded){
if(paused)recordedAudioFile.media.pause();
else recordedAudioFile.media.stop();
continue;
}
recordedAudioFile.duration = new Date().getTime() - recordedAudioFile.startTime;
// call release to free this created file so that it could get deleted for instance
recordedAudioFile.media.stopRecord();
recordedAudioFile.media.release();
recordedAudioFile.isBeingRecorded = true;
}
}
// START RECORDING
this.startAudioRecording = function() {
paused = false;
handleRecordedFileHold();
var dir = this.dir ? this.dir : '';
var filename = this.filename ? this.filename : 'recoredFiles';
var type = this.filetype ? this.filetype : 'mp3';
var src = dir + filename + (recordedAudioFiles.length + 1) + '.' + type;
var mediaRec = new Media(src,
function () {
console.log('recordAudio():Audio Success');
},
function (err) {
console.log('recordAudio():Audio Error: ' + err.code);
});
recordedAudioFiles.push({
media: mediaRec,
startTime: new Date().getTime()
});
mediaRec.startRecord();
}
// PAUSE RECORDING
this.pauseRecoredFiles = function () {
if(recordedAudioFiles.length){
paused = true;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
var recoredMedia = recordedAudioFiles[currentPosition.index].media;
recoredMedia.getCurrentPosition(
function (position) {
currentPosition.shift = position;
},
function (e) {
console.log("Error getting pos=" + e);
}
);
}
}
// PLAY RECORD
this.playRecordedFiles = function () {
handleRecordedFileHold();
var playNextFile = function () {
var recoredMedia = recordedAudioFiles[currentPosition.index];
if (recoredMedia) {
if(paused){
recoredMedia.media.seekTo(currentPosition.shift*1000);
paused = false;
}
recoredMedia.media.play();
currentPosition.timeout = setTimeout(function () {
currentPosition.index++;
recoredMedia.media.stop();
playNextFile();
}, recoredMedia.duration ? recoredMedia.duration : 0);
}
else{
paused = false;
currentPosition.index = currentPosition.shift = 0;
}
};
playNextFile();
}
// RESET PLAY
this.stopRecordedFiles = function () {
currentPosition.index = currentPosition.shift = 0;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
}
// REMOVE ALL RECORDED FILES
this.removeRecordedFiles = function() {
paused = false;
currentPosition.index = currentPosition.shift = 0;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
recordedAudioFiles = [];
}
};
var handler = new myRecordHandler();
// you can use this handler in your functions like this:
function recordAudio() {
// records one track and stops former track if there is one
handler.startAudioRecording();
}
function playAudio() {
handler.playRecordedFiles();
}
function pauseAudio() {
handler.pauseRecoredFiles();
}
function resumeAudio() {
pauseAudio();
recordAudio();
}
function stopAudio() {
handler.stopRecordedFiles();
}
Although I could not test your directory/filenames, because I do not have this directory created on my phone, these methods might help you to to store your files in a specific directory as well as with certain filenames:
handler.setDirectory('__YOUR_DIR__');
handler.setFilename('__YOUR_FILENAME__');
handler.setFileType('__YOUR_FILETYPE__');

Scraping data from clicked links on page then moving to next page & repeating in CasperJS

I'm struggling to get a casperjs to move on to the next page after it has recursively worked through the links on the page.
I can get it to take data from each page and move through the pages, or click on each link on a page, but I can't get it doing both.
var utils = require('utils');
var x = require('casper').selectXPath;
var casper = require('casper').create({
verbose: true,
logLevel: 'error',
waitTimeout: 10000,
pageSettings: {
loadImages: false,
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36'
}
});
var currentPage = 1;
var i = 0;
var links = [];
var link_titles = [];
var terminate = function() {
this.echo("Exiting..").exit();
};
function getSelectedPage() {
var el = document.querySelector('td.cur');
return parseInt(el.textContent);
}
function getPageLinks () {
var links = document.querySelectorAll('h3.r a');
return [].map.call(links, function(link) {
return link.getAttribute('href');
});
}
function getLinkData(link) {
this.thenOpen(link, function() {
var title = this.getTitle();
// Add the data from link
var data = {
title: title,
};
link_titles.push(data);
});
}
function loopThroughLinks() {
if( i < links.length) {
this.echo('[LINK #' + i + '] '+ links[i]);
getLinkData.call(this, links[i]);
i++;
this.run(loopThroughLinks);
} else {
utils.dump(link_titles);
}
}
function linkData(){
links = this.evaluate(getPageLinks);
this.run(loopThroughLinks);
}
var processPage = function() {
this.run(linkData);
//PROBLEM EXISTS BELOW HERE - IF YOU COMMENT OUT FROM HERE IT RUNS AS EXPECTED FOR THE FIRST PAGE
//WITH CODE BELOW INCLUDED, SKIPS this.run(linkData) AND JUST GOES THROUGH PAGES;
this.then(function(){
if (currentPage >= 3) {
return terminate.call(casper);
}
currentPage++;
this.echo("requesting next page: " + currentPage);
this.capture("google-results-p" + currentPage + ".png");
this.thenClick('a.pn span').then(function(){
this.waitFor(function(){
return currentPage === this.evaluate(getSelectedPage);
}, processPage, terminate);
});
}); //COMMENT OUT TO HERE FOR WORKING ONE PAGE VERSION
}
casper.start('https://www.google.co.uk/?gws_rd=ssl#q=casperjs');
casper.run(processPage);
Updated code to reflect multiple run calls. Now looping through first page corrrectly, but printing results from first page for all other pages??
var utils = require('utils');
var x = require('casper').selectXPath;
var casper = require('casper').create({
verbose: true,
logLevel: 'error',
waitTimeout: 10000,
pageSettings: {
loadImages: false,
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36'
}
});
var currentPage = 1;
var i = 0;
var links = [];
var link_titles = [];
var terminate = function() {
this.echo("Exiting..").exit();
};
function getSelectedPage() {
var el = document.querySelector('td.cur');
return parseInt(el.textContent);
}
function getPageLinks() {
var links = document.querySelectorAll("h3.r a");
return Array.prototype.map.call(links, function(e) {
try {
// google handles redirects hrefs to some script of theirs
return (/url\?q=(.*)&sa=U/).exec(e.getAttribute("href"))[1];
} catch (err) {
return e.getAttribute("href");
}
});
}
function getLinkData(link) {
this.thenOpen(link, function() {
//var title = this.fetchText('title');
var title = this.getTitle();
// Add the staff data from link
var data = {
title: title,
};
link_titles.push(data);
this.then(function(){ ///ADDED - BACK TO RIGHT PAGE FOR SELECTOR
this.back();
});
});
}
function loopThroughLinks() {
if( i < links.length) {
this.echo('[LINK #' + i + '] '+ links[i]);
getLinkData.call(this, links[i]);
i++;
this.then(loopThroughLinks);
} else {
utils.dump(link_titles);
}
}
function linkData(){
links = this.evaluate(getPageLinks);
this.then(loopThroughLinks);
}
var processPage = function() {
this.wait(2000, function(){
this.then(linkData);
});
this.wait(2000, function(){
this.then(function(){
if (currentPage >= 3) {
return terminate.call(casper);
}
this.echo("requesting next page: " + currentPage);
this.capture("google-results-p" + currentPage + ".png");
currentPage++;
this.thenClick('a.pn span').then(function(){
this.capture('google-results-2-p' + currentPage + '.png');
this.waitFor(function(){
return currentPage === this.evaluate(getSelectedPage);
}, processPage, terminate);
});
});
});
}
casper.start('https://www.google.co.uk/?gws_rd=ssl#q=casperjs');
casper.then(processPage);
casper.run();
You have to have only one casper.run() (and only one casper.start()) call. run() starts the CasperJS step queue and will finish execution if there are no further steps. The only call that needs to stay is casper.run(processPage);, but all other this.run(...) calls need to be changed to this.then(...).

SlimerJS is not running my script

I am trying to run my CasperJS test using slimerJS, and it just do nothing, opened the FF browser and displayed the SlimerJS logo. If I am trying to run a simple script like loading of Google homepage or something it works fine. Attached the script below, can you please tell me what is wrong there? Thanks!
// Simple messaging flow
action_helpers_v2 = require('../v2_modules/action_helpers_v2.js');
helpers_v2 = require('../v2_modules/helpers_v2.js');
var staging = casper.cli.get('staging'),
unixTimeStamp = (Date.now()).toString().substring(4),
currentTime = new Date(),
currentHour = currentTime.getHours(),
timeout = 15000;
var genereateText = function genereateText() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var mouse = require("mouse").create(casper);
var webPage = require('webpage');
var page = webPage.create();
var live = casper.cli.get("prod"),
staging = casper.cli.get("staging"),
localeTesting = casper.cli.get("localeTesting"),
buyerUserName = 'settings120',
buyerPassword = 123456,
orders_array = [],
numberOfTests = 0;
casper.test.begin("Test Name: simple messaging flow", function suite(test) {
casper.start('http://fiverr.com');
casper.then(function() {
if (staging) {
action_helpers_v2.enableStaging(staging);
}
});
casper.then(function() {
action_helpers_v2.navigateToHomepage();
});
casper.then(function() {
action_helpers_v2.login(buyerUserName,buyerPassword);
action_helpers_v2.navigateToConversation("yogev_a");
});
casper.wait(5000);
var message = genereateText();
casper.then(function() {
casper.evaluate(function(message) {
$('#message_body')[0].value = message;
}, message);
});
casper.then(function() {
casper.evaluate(function() {
$('.btn-send-message')[0].click()
});
});
casper.waitForText(message, function() {
casper.test.pass("Message was sent");
}, function() {
helpers_v2.printScreenAndMessage('message_error', 'message_error');
casper.test.fail("Message wasnt sent");
});
casper.run(function(){
test.done();
});
});

CasperJS evaluate() is not executing from within each() block

So I'm crawling a page, collecting links, then I would like to crawl those links to complete my dataset. Here's some code:
crawl.js:
var casper = require("casper").create({
waitTimeout: 3000,
pageSettings: {
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20130404 Firefox/23.0"
},
clientScripts: ["includes/jquery.min.js"],
verbose: true
});
var followers = require('./followers');
var currentPage = 1;
var x = require('casper').selectXPath;
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++
}
return size;
};
var collectFollowers = function() {
var url;
this.echo("capturing page " + currentPage);
this.capture("wowhead-p" + currentPage + ".png");
// don't go too far down the rabbit hole
if (currentPage >= 5 || !this.exists(x('//*[text()="Next ›"]'))) {
processFollowers.call(casper);
return terminate.call(casper);
}
currentPage++;
this.echo("requesting next page: " + currentPage);
url = this.getCurrentUrl();
var links = this.evaluate(function() {
var obj = {}
$('.listview-cleartext').map(function(){
obj[$(this).text()] = $(this).attr('href');
});
return obj;
});
for (key in links) {
followers.followers[key] = links[key];
}
this.echo("Page links: " + Object.size(followers.followers));
//this.emit('update.followers', links);
this.thenClick(x('//*[text()="Next ›"]')).then(function() {
this.waitFor(function() {
return url !== this.getCurrentUrl();
}, collectFollowers, processFollowers);
});
};
var processFollowers = function() {
this.echo("Total followers:" + Object.size(followers.followers));
this.each(Object.keys(followers.followers), function(casper, key) {
this.thenOpen('http://wowhead.com' + followers.followers[key]).then(function() {
this.echo("On http://wowhead.com" + followers.followers[key]);
this.evaluate(function() {
this.echo("Inside the evaluate statement.");
if ($('a[href=#quests]').length) {
this.echo("Has quest!");
$('a[href=#quests]').click();
var questURL = $('#tab-quests').show().find('.listview-cleartext').attr('href');
var questName = $('#tab-quests').show().find('.listview-cleartext').text();
this.echo("Quest URL: " + questURL);
followers.followers[key] = {"name": key, "quest": {"url": questURL, "name": questName}};
} else {
this.echo("Does not have quest!");
}
});
});
});
}
var terminate = function() {
this.echo("Done.").exit();
}
casper.start("http://wowhead.com/followers=2");
casper.waitForSelector(x('//*[text()="Next ›"]'), collectFollowers, processFollowers);
casper.run();
followers.js:
var require = patchRequire(require);
var utils = require('utils');
var followers = {};
exports.followers = followers;
followers is used to store a global variable, an object that I continually build and update as I crawl pages. So I go through 3 pages of data, collect links successfully, then begin to process them. As it stands, CasperJS appears to open each page successfully, however the evaluate function is never called.
I was able to get this functionality to work within PhantomJS with some async logic, but switched to casper because it appeared as though this would be taken care of under the hood. I've tried various combinations of thenOpen(), then() and open(), thenOpen() without the then(), etc.. What am I messing up?
casper.evalute() is the sandboxed page context in the same way the as the PhantomJS version (page.evaluate()). It has no access to variables defined outside.
this inside of evaluate() refers to window and not casper and I doubt that there is such a function like window.echo(). If you want to receive console messages from the page context, you need to register to the remote.message event:
casper.on("remote.message", function(msg){
this.echo("remote: " + msg);
});
You have to explicitly pass the result out of the page context and add it there:
var result = this.evaluate(function() {
console.log("Inside the evaluate statement.");
if ($('a[href=#quests]').length) {
console.log("Has quest!");
$('a[href=#quests]').click();
var questURL = $('#tab-quests').show().find('.listview-cleartext').attr('href');
var questName = $('#tab-quests').show().find('.listview-cleartext').text();
console.log("Quest URL: " + questURL);
return {"url": questURL, "name": questName}};
} else {
console.log("Does not have quest!");
return null;
}
});
if (result) {
followers.followers[key] = {name: key, quest: result};
}

Getting a "setVersion" is not a function error when using indexedDB

I tried to use following code to test the performance of IndexedDB.
The code is modified from http://www.html5rocks.com/en/tutorials/indexeddb/todo/ ,
It works well in chrome, but fails in Firefox 10, saying "db.setVersion is not a function".
I want to know how can I modify the code to make it work in firefox?
var count=0;
var MAX=10;
var times=3;
var allTime;
var stime;
var etime;
var html5rocks = {};
var indexedDB = window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB;
if ('webkitIndexedDB' in window) {
window.IDBTransaction = window.webkitIDBTransaction;
window.IDBKeyRange = window.webkitIDBKeyRange;
}
html5rocks.indexedDB = {};
html5rocks.indexedDB.db = null;
html5rocks.indexedDB.onerror = function(e) {
//console.log(e);
alert("Why didn't you allow my web app to use IndexedDB?!");
};
html5rocks.indexedDB.open = function(type) {
var request = indexedDB.open("todos");
request.onsuccess = function(e) {
var v = "1.20";
html5rocks.indexedDB.db = e.target.result;
var db = html5rocks.indexedDB.db;
// We can only create Object stores in a setVersion transaction;
if (v!= db.version) {
var setVrequest = db.setVersion(v);
// onsuccess is the only place we can create Object Stores
setVrequest.onerror = html5rocks.indexedDB.onerror;
setVrequest.onsuccess = function(e) {
if(db.objectStoreNames.contains("todo")) {
db.deleteObjectStore("todo");
}
var store = db.createObjectStore("todo",
{keyPath: "number"});
addTest();
};
}
else addTest();
};
request.onerror = html5rocks.indexedDB.onerror;
}
html5rocks.indexedDB.addTodo = function(todoText,num) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var data = {
"text": todoText,
"number": num
};
var request = store.put(data);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
getTest();
}
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.getTodo = function(id) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.get(id);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
delTest();
}
};
request.onerror = function(e) {
console.log("Error getting: ", e);
};
};
html5rocks.indexedDB.deleteTodo = function(id) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.delete(id);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
dataTest();
}
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.addData = function(d) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var data={
"text":d,
"number":1
};
var request = store.put(data);
request.onsuccess = function(e) {
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf()))+"<br/>";
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
function addTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.addTodo(' ',i);
}
function getTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.getTodo(Math.round(Math.random()*(MAX*times-1)+1));
}
function delTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.deleteTodo(i);
}
function dataTest() {
data=' ';
for(i=1;i<=21;i++)
data=data+data;
stime=new Date
html5rocks.indexedDB.addData(data);
}
function init() {
stime=new Date;
allTime=0;
html5rocks.indexedDB.open();
}
The spec is not finalized. This is currently shipped as the property mozIndexedDB in Gecko and webkitIndexedDB in Chrome until the standard is finalized. So you have to write for moz also. Now this code is only for webkit.
https://developer.mozilla.org/en/IndexedDB
setVersion() is Deprecated
The new way is to define the version in the IDBDatabase.open() method
firefox from version 10.0 implements open() with the new specification in which an indexeddb database IDBDatabase version is set as the second parameter of the open() method
example
var v = "1.20";
var request = indexedDB.open("todos", v);
html5 indexeddb javascript
The problem here is not the one chosen as the correct answer.
The problem is that the IndexedDB examples on HTML5Rocks were written to the pre-January IndexeDB spec. The working group has since published a breaking change going from the setVersion API to the new onupgradedneeded style.
Here, Firefox is technically correct to fail. Star this issue if you want to see Chrome do the same.

Categories

Resources