InjectJS

林一二2020年08月05日 15:10

我通过 WebCatalog Preload Script 注入的 UserScript。


// 将同步到云端的API暴露给Wiki/js

// https://www.electronjs.org/docs/api/context-bridge
const { contextBridge } = require('electron');
const path = require('path');

const wikiRepoPath = '/Users/linonetwo/Desktop/repo/wiki';
const scriptsPath = path.join(wikiRepoPath, 'scripts');
const { tiddlyWikiRepo, privateTiddlyWikiRepo, commitAndSync } = require(path.join(scriptsPath, 'watchWiki.js'));
const { isUnsync } = require(path.join(scriptsPath, 'checkGitState.js'));

contextBridge.exposeInMainWorld('wiki', {
  wikiPath: {
    tiddlyWikiRepo,
    privateTiddlyWikiRepo,
  },
  sync: (repoPath) => commitAndSync(repoPath),
  isUnsync: (repoPath) => isUnsync(repoPath),
});

// 无操作后定时刷新TiddlyWiki/js

const RELOAD_INTERVAL = 1000 * 60 * 60;
const CHECK_ACTIVITY_INTERVAL = 1000 * 3;

let time = new Date().getTime();

const refreshTime = () => {
  time = new Date().getTime();
};
document.addEventListener('keyup', refreshTime);
document.addEventListener('mousemove', refreshTime);
document.addEventListener('mouseup', refreshTime);

function refresh() {
    const serverNotStarted = !document || document.querySelector('.tc-site-title') === null;
    const notActivatedForLong = new Date().getTime() - time >= RELOAD_INTERVAL;
  if (serverNotStarted || notActivatedForLong) {
    window.location.reload(true);
  } else {
    setTimeout(refresh, CHECK_ACTIVITY_INTERVAL);
  }
}

setTimeout(refresh, CHECK_ACTIVITY_INTERVAL);