gm4-polyfill
Version:
A compatibility tool to ease making User Scripts compatible with both Greasemonkey 4 and other/older user script engines.
2 lines (1 loc) • 1.93 kB
JavaScript
"undefined"==typeof GM&&(this.GM={}),"undefined"==typeof GM_addStyle&&(this.GM_addStyle=e=>{let t=document.getElementsByTagName("head")[0];if(t){let n=document.createElement("style");return n.setAttribute("type","text/css"),n.textContent=e,t.appendChild(n),n}return null}),"undefined"==typeof GM_registerMenuCommand&&(this.GM_registerMenuCommand=(e,t,n)=>{if(!document.body)return void("loading"===document.readyState&&document.documentElement&&"html"===document.documentElement.localName?new MutationObserver(((o,d)=>{document.body&&(d.disconnect(),GM_registerMenuCommand(e,t,n))})).observe(document.documentElement,{childList:!0}):console.error("GM_registerMenuCommand got no body."));let o=document.body.getAttribute("contextmenu"),d=o?document.querySelector("menu#"+o):null;d||(d=document.createElement("menu"),d.setAttribute("id","gm-registered-menu"),d.setAttribute("type","context"),document.body.appendChild(d),document.body.setAttribute("contextmenu","gm-registered-menu"));let u=document.createElement("menuitem");u.textContent=e,u.addEventListener("click",t,!0),d.appendChild(u)}),"undefined"==typeof GM_getResourceText&&(this.GM_getResourceText=e=>GM.getResourceUrl(e).then((e=>fetch(e))).then((e=>e.text())).catch((function(e){return GM.log("Request failed",e),null}))),Object.entries({log:console.log.bind(console),info:GM_info}).forEach((([e,t])=>{t&&void 0===GM[e]&&(GM[e]=t)})),Object.entries({GM_addStyle:"addStyle",GM_deleteValue:"deleteValue",GM_getResourceURL:"getResourceUrl",GM_getValue:"getValue",GM_listValues:"listValues",GM_notification:"notification",GM_openInTab:"openInTab",GM_registerMenuCommand:"registerMenuCommand",GM_setClipboard:"setClipboard",GM_setValue:"setValue",GM_xmlhttpRequest:"xmlHttpRequest",GM_getResourceText:"getResourceText"}).forEach((([e,t])=>{let n=this[e];n&&void 0===GM[t]&&(GM[t]=function(...e){return new Promise(((t,o)=>{try{t(n.apply(this,e))}catch(e){o(e)}}))})}));