2016-08-25 28 views
0

我正在用tampermonkey編寫腳本。保留在腳本中設置的變量

我有一個var arr = ["alex", "felix"]它可以根據腳本的使用情況進行更新。當有變化時,我將值添加到arr中; arr.push("kelix")

但是當腳本重新加載時,arr仍然是var arr = ["alex", "felix"]。 newValue不會推送到數組。那麼如何保留變量arr中的更改呢?

我該怎麼辦?

+1

使用localStorage的/ sessionStorage的存儲變量refresh.'sessionStorage.setItem後重新使用( '改編',編曲):'和'使用sessionStorage.getItem( '改編')進行檢索;'。有關sessionStorage的更多信息,請訪問:https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage –

+0

您可以直接使用'localStorage.arr' – maioman

回答

1

我會用localStorage。下面看到的示例腳本,將允許您更改文檔標題,並記住它在重裝:在控制檯

// ==UserScript== 
// @name  Remember value 
// @namespace util 
// @description Test that remembers any saved value after reload 
// @include  http://stackoverflow.com/* 
// @version  1 
// @grant  none 
// ==/UserScript== 
// Try to load saved data from local storage 
const FIELD_NAME = "userscript_TEST"; 
var saved = localStorage[FIELD_NAME]?JSON.parse(localStorage[FIELD_NAME]):{}; 

// Save data when leaving tab 
window.addEventListener("unload", function() { 
    localStorage[FIELD_NAME] = JSON.stringify(saved); 
}); 
// This changed document title and remembers it 
window.changeDocumentTitleForever = function(title) { 
    saved["title"] = title; 
    document.title = title; 
} 

// This loads title after loading page 
if(saved.title) 
    document.title = saved.title; 

用法:

changeDocumentTitleForever("test") 
0

如果你正在寫userscript,GM_setValueGM_getValue可能是一個更好選擇比localStorage

var arr = ["alex", "felix"]; 
try { arr = JSON.parse(GM_getValue('arr', '["alex", "felix"]')); } 
catch (_ignore) { /* ignore when JSON.parse fail */ } 
// do something with arr 
arr.push('kelix'); 
GM_setValue('arr', JSON.stringify(arr)); 
相關問題