How to respond to multiple bookmark operations in Chrome?

I’m working on a simple Chrome extension which deals with bookmarks.
So far I’ve discovered two ways to respond to operations that the chrome.bookmarks API provides:

  • pass callback function directly to the API call (eg. chrome.bookmarks.move(string id, object destination, function callback))
  • register callback function globally (chrome.bookmarks.onMoved.addListener(function callback))

As far as I know (ran some tests), when I use the first option (direct callback), the state of the bookmark tree is not updated yet, and the global callback does not accept any data, only ids and indices are present in the move info (reference).

However, when multiple bookmarks are moved, the move function must be called for each, because it accepts only one id, and moves the corresponding bookmark (or folder).

What I’d like to do is to refresh the extension page after the last bookmark operation is finished (eg. 10 bookmarks are being moved, it requires 10 async API calls, and I’d like to do a refresh after the last).

Note: I implemented this as a callback chain, so I know which was the last operation (but – as I mentioned – passing callback to the last does not work, and I’d rather like to see a stack overflow because of the recursion than nothing at all).
(But SO is unlikely because of the async nature I guess.)

My move function:

this.chromeMoveCallback = function(elementIds, parentId, index) {
	var nodeId = elementIds.shift();
	if (nodeId !== undefined) {
		var destination = {};
		if (parentId !== undefined && parentId !== null) {
			destination.parentId = parentId;
		}
		if (index !== undefined && index !== null) {
			destination.index = index;
		}
		chrome.bookmarks.move(
			nodeId,
			destination,
			this.chromeMoveCallback(elementIds, parentId, index) // chain
		);
	} else {
		// no elements left, refresh window ???
		this.refresh(app.refreshPanels.bind(app));
	}
};


Source: bookmarks

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.