Skip to content

Instantly share code, notes, and snippets.

@oscardoudou
Created March 12, 2022 22:47
Show Gist options
  • Select an option

  • Save oscardoudou/1cff897e6d04bcc9e2bcec9d5d282801 to your computer and use it in GitHub Desktop.

Select an option

Save oscardoudou/1cff897e6d04bcc9e2bcec9d5d282801 to your computer and use it in GitHub Desktop.
adopt GM.getValue GM.setValue and compatible with GM_getValue GM_setValue
// ==UserScript==
// @name adopt GM.getValue GM.setValue and compatible with GM_getValue GM_setValue
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author ychz
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @include *
// @grant GM.getValue
// @grant GM.setValue
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
var globalValue;
//GM4 is true for tampermonkey, meaning tampermonkey has GM.getValue API
//it's just tampermonkey GM_getValue also works, and it works synchronizedly
let GM4 = (typeof GM.getValue === 'undefined') ? false : true;
//to test non GM4 compatible simply comment line ^ and uncomment line below
//let GM4 = false;
let key = 'testKey';
//storage default to empty array if no prior value being persisted to storage
getStorage(key, []);
(function(){
'use strict';
//add a button to the top of the page, storage value would change on click
let button = document.createElement('Button')
button.id = 'button'
button.innerHTML = "I'm the button"
button.addEventListener('click',function(){
setStorage(key, 100) }
)
document.body.prepend(button)
//click the button within 5s after page load, you should see updated value
setTimeout(() => getStorage(key, []), 5000)
})();
//to use GM.getValue or GM.setValue you have to wrap it in async await or use the value in callback then
function getStorage(key, defaultValue){
if(!GM4){
console.log('not GM4')
globalValue = GM_getValue(key, defaultValue)
console.log("globalValue: "+globalValue)
}else{
GM.getValue(key, defaultValue).then(x => {globalValue = x; console.log("globalValue: "+globalValue)});
}
}
//to use GM.getValue or GM.setValue you have to wrap it in async await or use the value in callback then
async function setStorage(key, value){
if(!GM4){
console.log('not GM4')
globalValue.push(value)
GM_setValue(key, globalValue)
}else{
globalValue.push(value)
await GM.setValue(key, globalValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment