Backup Chrome tabs with JSTalk

Sometimes Chrome has trouble restoring its windows and tabs upon launch (the windows and tabs open, but their content never loads). The worst thing about this bug is that it tends to happen only when I have large number of windows and tabs to restore.

I’ve added the following JSTalk script to my nightly backup routine. It writes out the names and URLs of all open tabs to a text file:

var chrome = [SBApplication application:'Google Chrome'];
var windows = SBElementArrayToJSArray([chrome windows]);
var output = '';
windows.forEach(function(window){
    var windowName = [window name];
    if (windowName != 'New Tab') {
        var tabs = SBElementArrayToJSArray([window tabs]);

        output += windowName + '\n';
        tabs.forEach(function(tab){
            output += '\t' + [tab title] + '\n';
            output += '\t' + [tab URL] + '\n\n';
        });
    }
});

Date.prototype.getShortWeekdayName = function(){
    return ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][this.getDay()];
};
var tabsBackupFileName = 'tabs_' + (new Date()).getShortWeekdayName() + '.txt';
var tabsBackupFilePath = [@"~/Documents/backup/browser" stringByExpandingTildeInPath];
tabsBackupFilePath = [tabsBackupFilePath stringByAppendingPathComponent: tabsBackupFileName];

[[NSString stringWithString:output] writeToFile:tabsBackupFilePath atomically:NO encoding:NSUTF8StringEncoding error:nil];

function SBElementArrayToJSArray(sbArray) {
    var sbIdx = 0;
    var sbCount = [sbArray count];
    var result = [];
    for (; sbIdx < sbCount; sbIdx++) {
        result.push([sbArray objectAtIndex:sbIdx]);
    }
    return result;
}

It uses Cocoa’s Scripting Bridge to enable JSTalk to talk to Chrome via its AppleScript interface.

chrome jstalk Apr 22 2012