I believe this is a follow on from the following questions, and so I will combine them all into a single code example that runs in the background scope (background.js): realtime with non-event programming, crossrider: store snapshot of bookmarks in local database and compare to current bookmarks list
So for the getChanges function, I prefer to convert the bookmark trees into hash lists and then compare the lists for changes. In the following example, I use createHash to create the hash lists using cloneNode to create a shallow clone of the node objects, and then in getChanges I compare the hash lists for additions, modifications, and deletions:
appAPI.ready(function() {
// Poll every 30 seconds
setInterval(function() {
appAPI.db.async.get('prevBookmarks', function(value) {
// Load or initialize the previous bookmarks list
var prevBookmarks = (value) ? value : {};
// Get current bookmarks
appAPI.bookmarks.getTree(function(nodes) {
// Save bookmark hash for comparison in next interval
appAPI.db.async.set('prevBookmarks', createHash(nodes[0]));
// Get hash list of curent bookmarks
var currBookmarks = createHash(nodes[0]);
// Get changes between the lists
var changes = getChanges(prevBookmarks, currBookmarks);
// Post changes to your API server
appAPI.request.post({
url: http://yourAPIserver.com,
postData: changes,
contentType: 'application/json'
});
});
});
}, 30 * 1000);
// Function to create a hash list from a bookmark tree
function createHash(node) {
var hash = {};
if (typeof node === 'object') hash[node._id] = cloneNode(node);
if (node.isFolder && typeof node.children !== 'undefined' && node.children.length > 0) {
node.children.forEach(function(child) {
var childHash = createHash(child);
for (var key in childHash) {
if (!hash[key]) hash[key] = cloneNode(childHash[key]);
}
});
}
return hash;
}
// Function to create shallow clones of bookmark nodes
function cloneNode(node) {
var clone = appAPI.JSON.parse(appAPI.JSON.stringify(node));
delete clone.children;
delete clone.dateAdded;
return clone;
}
// Get changes between current and previous bookmark hash lists
function getChanges(prev, curr) {
// Initialize return object
var changes = {added:{}, modified:{}, removed:{}};
// Search for added or modified nodes
for (var key in curr) {
if (!prev[key])
changes.added[key] = curr[key];
else if (appAPI.JSON.stringify(prev[key]) !== appAPI.JSON.stringify(curr[key]))
changes.modified[key] = curr[key];
}
// Search for removed nodes
for (var key in prev) {
if (!curr[key])
changes.removed[key] = prev[key];
}
return changes;
}
});
Disclaimer: I am a Crossrider employee