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) • 2.12 kB
JavaScript
"undefined"==typeof GM&&((void 0).GM={}),"undefined"==typeof GM_addStyle&&((void 0).GM_addStyle=function(e){var t=document.getElementsByTagName("head")[0];if(t){var n=document.createElement("style");return n.setAttribute("type","text/css"),n.textContent=e,t.appendChild(n),n}return null}),"undefined"==typeof GM_registerMenuCommand&&((void 0).GM_registerMenuCommand=function(e,t,n){if(document.body){var o=document.body.getAttribute("contextmenu"),u=o?document.querySelector("menu#"+o):null;u||((u=document.createElement("menu")).setAttribute("id","gm-registered-menu"),u.setAttribute("type","context"),document.body.appendChild(u),document.body.setAttribute("contextmenu","gm-registered-menu"));var d=document.createElement("menuitem");d.textContent=e,d.addEventListener("click",t,!0),u.appendChild(d)}else"loading"===document.readyState&&document.documentElement&&"html"===document.documentElement.localName?new MutationObserver((function(o,u){document.body&&(u.disconnect(),GM_registerMenuCommand(e,t,n))})).observe(document.documentElement,{childList:!0}):console.error("GM_registerMenuCommand got no body.")}),"undefined"==typeof GM_getResourceText&&((void 0).GM_getResourceText=function(e){return GM.getResourceUrl(e).then((function(e){return fetch(e)})).then((function(e){return e.text()})).catch((function(e){return GM.log("Request failed",e),null}))}),Object.entries({log:console.log.bind(console),info:GM_info}).forEach((function(e){var t=e[0],n=e[1];n&&void 0===GM[t]&&(GM[t]=n)})),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((function(e){var t=e[0],n=e[1],o=undefined[t];o&&void 0===GM[n]&&(GM[n]=function(){for(var e=this,t=arguments.length,n=new Array(t),u=0;u<t;u++)n[u]=arguments[u];return new Promise((function(t,u){try{t(o.apply(e,n))}catch(e){u(e)}}))})}));