Using javascript for pinging a webapp to keep session open

前端 未结 6 727
一个人的身影
一个人的身影 2021-01-31 10:26

I\'m writing a greasemonkey script to keep session open on a webapp I use for work. Which javascript command would you use to create some feedback with the server and ensure the

6条回答
  •  梦谈多话
    2021-01-31 10:52

    Using some tips from Jesse's answer, here's the complete code.

    You will need to update the @match param with your site's domain

    // ==UserScript==
    // @name         Auto session extender
    // @namespace    http://obive.net/
    // @version      0.2
    // @description  Automatically extend server-side session
    // @author       Charlie Hayes
    // @match        http://obive.net/
    // @grant   GM_getValue
    // @grant   GM_setValue
    // @noframes
    // ==/UserScript==
    
    (function() {
        'use strict';
    
        console.log('The session for this site will be extended automatically via userscript.');
    
        var minute = 60*1000;
        var refreshTime = 15 * minute;
    
        var iframe = document.createElement("iframe");
        iframe.style.width = 0;
        iframe.style.height=0;
    
        var loc = window.location;
        var src = loc.protocol +'//' + loc.host + loc.pathname;
        src += loc.search ? (loc.search + '&') : '?';
        src +=  'sessionextendercachebuster=';
    
        var reloadIframe = function(){
            var time = new Date().getTime();
            var lastRefresh = GM_getValue('lastRefresh');
            var timeSinceLastRefresh = time - lastRefresh;
            if (!lastRefresh || timeSinceLastRefresh > refreshTime - minute) {
                console.log('Auto-extending session');
                iframe.src = src + time;
                GM_setValue('lastRefresh',time);
                setTimeout(reloadIframe, refreshTime);
    
                setTimeout(function(){
                    // Unload the iframe contents since it might be taking a lot of memory
                    iframe.src='about:blank';
                },10000);
            }else{
                console.log('Another tab/window probably refreshed the session, waiting a bit longer');
                setTimeout(reloadIframe, refreshTime - timeSinceLastRefresh - minute);
            }
        };
        setTimeout(reloadIframe, refreshTime);
        document.body.appendChild(iframe);
    })();
    

提交回复
热议问题