AutoSave Sessions Mod


  • Moderator

    What
    Periodically (every (default 5) minutes), save the current browser session using Vivaldi's saved sessions functionality.

    It will keep the last (default 5) sessions.

    You can them open them from the usual place:
    0_1544785401599_6ea91ff5-6415-4f54-8258-3ad0bb860c24-image.png

    Installation
    As a custom.js mod:

    /*
    * Autosave Sessions (a mod for Vivaldi)
    * Written by LonM
    * v2 : Better handling of multiple windows
    */
    
    (function autoSaveSessionsMod(){
    "use strict";
    
    /*
     * Autosave Prefix must be a unique name
     *   don't use it in your mnually saved sessions!
     *   It has to be a compatible file name,
     *   so avoid space, brackets, special characters etc.
     *   also, it can't be blank!
     */
    const SESSION_AUTOSAVE_PREFIX = "VSESAUTOSAVE_";
    
    /*
     * Delay (Minutes) defines how frequently an autosave should happen
     *     delay should be greater than 0
     *     Just change the first value (the MINUTES value)
     */
    const SESSION_AUTOSAVE_DELAY_MINUTES = 5;
    const SESSION_AUTOSAVE_DELAY = SESSION_AUTOSAVE_DELAY_MINUTES * 1000 * 60;
    
    /*
    *  Max old sessions says how many old sessions to keep
    *     Oldest sessions are deleted if there are too many
    *     Set to Infinity to keep all sessions
    */
    const SESSION_AUTOSAVE_MAX_OLD_SESSIONS = 5;
    
    /**
     * Variable validations
     */
    if(SESSION_AUTOSAVE_DELAY <= 30 * 1000){
        console.error("Session autosave delay must be greater than 30 seconds");
        return;
    }
    if(SESSION_AUTOSAVE_PREFIX === ""){
        console.error("Session autosave premix must not be empty string");
        return;
    }
    if(SESSION_AUTOSAVE_MAX_OLD_SESSIONS <= 0){
        console.error("Session autosave must keep at least 1 old session");
        return;
    }
    
    /**
     * Enable Autosaving sessions
     */
    function autoSaveSession(){
        vivaldi.sessionsPrivate.getAll(allSessions => {
            const now = new Date();
            const autosavesOnly = allSessions.filter(x => x.name.indexOf(SESSION_AUTOSAVE_PREFIX)===0);
            const oldestFirst = autosavesOnly.sort((a,b) => {return a.createDateJS - b.createDateJS;});
    
            /* create the new session */
            const name = SESSION_AUTOSAVE_PREFIX + now.toISOString().replace(":",".").replace(":",".");
            const options = {
                saveOnlyWindowId: 0
            };
            vivaldi.sessionsPrivate.saveOpenTabs(name, options, () => {});
    
            /* delete older sessions */
            let numberOfSessions = oldestFirst.length + 1; /* length + 1 as we have just added a new one */
            let oldestIndex = 0;
            while(numberOfSessions > SESSION_AUTOSAVE_MAX_OLD_SESSIONS){
                vivaldi.sessionsPrivate.delete(oldestFirst[oldestIndex].name,() => {});
                oldestIndex++;
                numberOfSessions--;
            }
        });
    }
    
    /**
     * Check if this is the most recent window, and if the most recent window is still open
     * if not, then stop saving the sessions
     */
    function triggerAutosave(){
        chrome.storage.local.get("lonm.autosave.lastOpenedWindow", data => {
            const lastOpenedWindow = data["lonm.autosave.lastOpenedWindow"];
            if(vivaldiWindowId===lastOpenedWindow){
                /* We know this window is correct, skip the checks */
                autoSaveSession();
                return;
            }
            chrome.windows.getAll(openWindows => {
                const foundLastOpen = openWindows.find(window => window.id===lastOpenedWindow);
                if(foundLastOpen){
                    /*Most recent window still active, use that one instead*/
                } else {
                    /*Most recent window was closed, revert to this one*/
                    chrome.storage.local.set({
                        "lonm.autosave.lastOpenedWindow": vivaldiWindowId
                    }, () => {
                        autoSaveSession();
                    });
                }
            });
        });
    }
    
    /**
     * Init the mod, but only if we are not incognito, to maintain privacy.
     * Save the window id in storage, and only use the most recent window to save sessions
     */
    function init(){
        if(window.vivaldiWindowId){
            chrome.windows.getCurrent(window => {
                if(!window.incognito){
                    chrome.storage.local.set({
                        "lonm.autosave.lastOpenedWindow": vivaldiWindowId
                    }, () => {
                        setInterval(triggerAutosave, SESSION_AUTOSAVE_DELAY);
                    });
                }
            });
        } else {
            setTimeout(init, 500);
        }
    }
    
    init();
    
    })();
    
    

    Remarks
    When you are configuring the mod, read the comments carefully, as there are caveats to the kind of session name you can use, how often to save.

    If you want to keep every single old session (NOT RECOMMENDED), use Infinity - type it just like that, no quotes, it's a valid javascript value. This will probably break your system through filling your disk storage space up, but if you want the option - it's there.

    There is a feature request for session autosave, but this only refers to saving when you are about to close vivaldi. This mod is totally different, instead autosaving as you browse (e.g. if for some reason your machine is particularly crash-prone).

    Changelog

    • Better handling of multiple windows
    • Initial release


  • wonderful, keeping it just in case 🙂



  • For whatever reason the console spits out this on my computer

    Refused to load the script 'file:///I:/VIVALDI/_MOD/aoutosaveSession.js' because it violates the following Content Security Policy directive: "script-src 'self' http://localhost:35729/". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

    even with a squeaky clean fresh stand alone install ...


  • Moderator

    @QuHno I have a couple of extra Qs:

    • Which version of vivaldi are you using?
    • Did this mod work on previous versions?
    • How are you installing the mod?
    • Do you have any local servers running at localhost:35729 ? That's the most confusing part of this...

    Also, is there a typo in aoutosaveSession?



  • @LonM

    • I've tried it in all versions from 2.6.1566.44 (stable) to 2.7.1593.1 (sopranos) all as stand alone in the 32 and 64 bit versions on Win 7 and 10
    • Don't know about older versions, not tested yet, I just installed it yesterday because I was curious how well it works
    • By adding a <script src="..."></script> line after the other script lines to the browser.html And yes, I made sure that it is UTF-8 and has UNIX LF
    • Nope, only an on demand server on port 8080 and it was off at the time I tested it.
    • If there is a typo, it is in the original script, I only copy pasted it unchanged - and even if there were an c/p error or a typo, it should give another error and not the CSP violation error I get 😃

    ... but I wonder why you do not get the error, because I've found this specific CSP in the [path to Vivaldi]\Application[version number]\resources.pak

    "app": {
        "background": {
          "scripts": [
            "background-common-bundle.js",
            "background-bundle.js"
          ]
        },
        "content_security_policy": "script-src 'self' http://localhost:35729/; object-src 'self'"
      },
    

    PS: Basically I don't need the mod. I make daily compressed backups and I know how to save sessions if I want to make sure they don't go lost (something that should get more advertised in the UI, or else there would be less bug reports) 🙂



  • OK, problem solved:

    It is only possible to "install" this mod directly in the
    [path to]\Application\#.#.####.#\resources\vivaldi
    folder, or in a subfolder inside of that folder.

    I tried it like I did with my mods some years ago in a path beneath the the Application folder, but that does not work because above mentioned CSP.



  • @LonM Hi, thanks for this awesome mod.

    I have using you mod for a while now, & I think there is a glitch with multiple opened windows, which could cause creating unlimited save session at once until i run out of disk space. I have setup to only keep 2 copy of saved session & repeat every 15 mins.

    Thanks again.


  • Moderator

    @dude99 Oh no, that sounds bad. I'll take a look at it.


  • Moderator

    @dude99 Hi,

    Do you have any screenshots or names of the session files? That would be helpful in debugging this.



  • @LonM I will try to get it next time around, have to wait for it to happen again... LOL


  • Moderator

    @dude99 Thanks.



  • @LonM There, it glitched half an hour ago:

    autosaveGlitch.png


  • Moderator

    @dude99 OK. It looks like the interval is being triggered once every millisecond which isn't good. 😬

    Some additional Qs:

    • How many windows do you have open?
    • Which version of vivaldi are you in?


  • @LonM Now I have 10 windows, I don't think it happen when I only have 1 window opened. Using latest stable 2.7.1628.30, but it keep happening since I begin using it about a few weeks ago.


  • Moderator

    @dude99 I've updated the original post with a newer version to test. Does this work better?



  • @LonM Thanks, I'm testing it now.
    will report back afterward.



  • @LonM Hi, I have tested it for 48 hours & it seems you have fixed it! Congratulation & thanks a lot! 🤟🏼


  • Moderator

    @dude99 Good to hear 🙂



  • @LonM Hi, sorry to bother you again... I just wonder, is it possible to drop this JS into the extension page (dev mode) & turn it into an extension?


  • Moderator

    @dude99 It would be easy to do that.... but not right now.

    If the developers of vivaldi would open the internal API to extensions, perhaps behind some kind of 'sessions' permission, then yes, then it would be possible.


Log in to reply
 

Looks like your connection to Vivaldi Forum was lost, please wait while we try to reconnect.