{"id":14989074,"url":"https://github.com/chocolateboy/gm-compat","last_synced_at":"2025-04-12T01:21:16.892Z","repository":{"id":44338074,"uuid":"293124524","full_name":"chocolateboy/gm-compat","owner":"chocolateboy","description":"Portable monkey-patching for userscripts","archived":false,"fork":false,"pushed_at":"2021-03-01T23:00:40.000Z","size":145,"stargazers_count":15,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-25T21:03:15.982Z","etag":null,"topics":["clone-into","cloneinto","export-function","exportfunction","greasemonkey","shim","tampermonkey","unsafe-window","unsafewindow","userscript","userscripts","violentmonkey","zero-dependency"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"artistic-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chocolateboy.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-09-05T17:36:55.000Z","updated_at":"2025-03-12T23:53:47.000Z","dependencies_parsed_at":"2022-09-19T04:00:36.621Z","dependency_job_id":null,"html_url":"https://github.com/chocolateboy/gm-compat","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chocolateboy%2Fgm-compat","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chocolateboy%2Fgm-compat/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chocolateboy%2Fgm-compat/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chocolateboy%2Fgm-compat/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chocolateboy","download_url":"https://codeload.github.com/chocolateboy/gm-compat/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248501855,"owners_count":21114684,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clone-into","cloneinto","export-function","exportfunction","greasemonkey","shim","tampermonkey","unsafe-window","unsafewindow","userscript","userscripts","violentmonkey","zero-dependency"],"created_at":"2024-09-24T14:17:39.747Z","updated_at":"2025-04-12T01:21:16.868Z","avatar_url":"https://github.com/chocolateboy.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gm-compat\n\n[![NPM Version](https://img.shields.io/npm/v/gm-compat.svg)](https://www.npmjs.org/package/gm-compat)\n\n\u003c!-- TOC --\u003e\n\n- [NAME](#name)\n- [FEATURES](#features)\n- [INSTALLATION](#installation)\n- [USAGE](#usage)\n- [DESCRIPTION](#description)\n  - [Why?](#why)\n  - [Why not?](#why-not)\n- [TYPES](#types)\n- [API](#api)\n  - [apply](#apply)\n  - [call](#call)\n  - [cloneInto](#cloneinto)\n  - [export](#export)\n  - [exportFunction](#exportfunction)\n  - [unsafeWindow](#unsafewindow)\n  - [unwrap](#unwrap)\n- [COMPATIBILITY](#compatibility)\n- [DEVELOPMENT](#development)\n- [SEE ALSO](#see-also)\n- [VERSION](#version)\n- [AUTHOR](#author)\n- [COPYRIGHT AND LICENSE](#copyright-and-license)\n\n\u003c!-- TOC END --\u003e\n\n# NAME\n\ngm-compat - portable monkey-patching for userscripts\n\n# FEATURES\n\n- Portable access to:\n  - [`unsafeWindow`][unsafeWindow]\n  - [`cloneInto`][cloneInto]\n  - [`exportFunction`][exportFunction]\n- ~ 750 B minified\n- CDN builds ([unpkg][], [jsDelivr][])\n\n# INSTALLATION\n\n```\n$ npm install gm-compat\n```\n\n# USAGE\n\n```javascript\n// ==UserScript==\n// @name          My Userscript\n// @description   A userscript which hooks XMLHttpRequest#open\n// @include       https://www.example.com/*\n// @require       https://unpkg.com/gm-compat@1.1.0\n// ==/UserScript==\n\nconst xhrProto = GMCompat.unsafeWindow.XMLHttpRequest.prototype\nconst oldOpen = xhrProto.open\n\nfunction open (method, url) {\n    if (url === TARGET) {\n        this.addEventListener('load', () =\u003e {\n            process(this.responseText)\n        })\n    }\n\n    GMCompat.apply(this, oldOpen, arguments)\n}\n\nxhrProto.open = GMCompat.export(open)\n```\n\n# DESCRIPTION\n\ngm-compat is a tiny compatibility shim for userscripts which provides uniform,\ncross-engine access to [`unsafeWindow`][unsafeWindow], [`cloneInto`][cloneInto]\nand [`exportFunction`][exportFunction]. These can be used to portably modify\npage properties, e.g. to hook [`XMLHttpRequest#open`][xhr#open] to intercept\nHTTP requests.\n\nModifications to a page's window (`unsafeWindow`) need to use the `cloneInto`\nand `exportFunction` functions on Firefox. However, these functions are not\navailable by default in Chrome. In addition, `unsafeWindow` is not the actual\n`unsafeWindow` object in all engines.\n\nSince the functions are needed on Firefox, the options for writing portable\nscripts which modify page properties are either to implement\nbrowser/engine-specific code in each script or to use a shim which exposes an\nAPI that works with all engines. gm-compat provides an implementation of the\nlatter.\n\nWhen the functions are not needed (i.e. in Chrome), they're implemented as\npass-through (identity) functions, so they work consistently in all cases.\n\nNote that `GMCompat` is a local variable (declared with `const`), not a\nproperty of the window object. This ensures that each script running on a page\ncan have its own isolated version of gm-compat without conflicts.\n\n## Why?\n\nBecause writing portable code which modifies page properties is error-prone and\nlong-winded. This shim aims to abstract away the inconsistencies and\nincompatibilities so that scripts don't need to reinvent it.\n\n## Why not?\n\nThere may be no need to use this if scripts don't require Greasemonkey APIs and\nare able to operate directly in the page context (i.e. `@grant none`), although\nnote that `@grant none` is [not supported][grant-none] by all engines, and\n`@grant none` (and `unsafeWindow`) doesn't portably work on [all sites][csp].\n\n# TYPES\n\nThe following types are referenced in the descriptions below.\n\n```typescript\ntype CloneIntoOptions = {\n    cloneFunctions?: boolean;\n    target?: object;\n    wrapReflectors?: boolean;\n};\n\ntype ExportOptions = {\n    target?: object;\n};\n\ntype ExportFunctionOptions = {\n    allowCrossOriginArguments?: boolean;\n    defineAs?: string;\n    target?: object;\n};\n```\n\n# API\n\n## apply\n\n**Type**: `\u003cA extends ArrayLike, R\u003e($this: any, fn: ((...args: A) =\u003e R), args: A) =\u003e R`\n\nSafely call a page function with an `arguments` object or array of arguments\nfrom the script context. This is needed to avoid security errors when passing\narguments from the script to the page, e.g.:\n\nThis doesn't work:\n\n```javascript\nfunction open (method, url) {\n    if (url === TARGET) // ...\n\n    // XXX Error: Permission denied to access property \"length\"\n    oldOpen.apply(this, arguments)\n}\n```\n\nThis works:\n\n```javascript\nfunction open (method, url) {\n    // ...\n    GMCompat.apply(this, oldOpen, arguments) // OK\n}\n```\n\n## call\n\n**Type**: `\u003cA extends any[], R\u003e($this: any, fn: ((...args: A) =\u003e R), ...A) =\u003e R`\n\nSafely call a page function with arguments from the script context. This is\nneeded to avoid security errors when passing arguments from the script to the\npage, e.g.:\n\nThis doesn't work:\n\n```javascript\n// XXX Error: Permission denied to access property \"value\"\nGMCompat.unsafeWindow.notify('loaded', { value: 42 })\n```\n\nThis works:\n\n```javascript\nGMCompat.call(undefined, GMCompat.unsafeWindow.notify, 'loaded', { value: 42 }) // OK\n```\n\n## cloneInto\n\n**Type**: `\u003cT extends object\u003e(object: T, options?: CloneIntoOptions) =\u003e T`\n\nPortable access to Firefox's [`cloneInto`][cloneInto] function, which returns a\nversion of the supplied object that can be accessed in the provided context.\n\n```javascript\nconst dummyPerformance = {\n    now () { ... }\n}\n\nGMCompat.unsafeWindow.performance = GMCompat.cloneInto(dummyPerformance)\n```\n\nIf no options are supplied, the default values are:\n\n```javascript\n{ cloneFunctions: true, target: GMCompat.unsafeWindow, wrapReflectors: true }\n```\n\nIf supplied, they are merged into/override the defaults.\n\n## export\n\n**Type**:\n- `\u003cT extends Function\u003e(value: T, options?: ExportOptions) =\u003e T`\n- `\u003cT extends object\u003e(value: T, options?: ExportOptions) =\u003e T`\n\nA wrapper function which delegates to [`cloneInto`](#cloneinto) or\n[`exportFunction`](#exportFunction), depending on the type of its argument,\ni.e.:\n\n```javascript\nconst fn = () =\u003e { ... }\nGMCompat.export(fn)\n```\n\nis equivalent to:\n\n```javascript\nGMCompat.exportFunction(fn)\n```\n\nand:\n\n```javascript\nconst obj = { ... }\nGMCompat.export(obj)\n```\n\nis equivalent to:\n\n```javascript\nGMCompat.cloneInto(obj)\n```\n\nAn optional options object can be supplied to override the default target\n([`unsafeWindow`](#unsafeWindow)). This is passed as the options parameter to\n[`cloneInto`](#cloneInto) or [`exportFunction`](#exportFunction) and merged\ninto their default options.\n\n```javascript\nGMCompat.export(obj, { target: iframe })\n```\n\n## exportFunction\n\n**Type**: `\u003cT extends Function\u003e(fn: T, options?: ExportFunctionOptions) =\u003e T`\n\nPortable access to Firefox's [`exportFunction`][exportFunction] function, which\nreturns a version of the supplied function that can be executed in the provided\ncontext.\n\n```javascript\nfunction log () { }\n\nGMCompat.unsafeWindow.log = GMCompat.exportFunction(log)\n```\n\nIf no options are supplied, the default values are:\n\n```javascript\n{ allowCrossOriginArguments: false, target: GMCompat.unsafeWindow }\n```\n\nIf supplied, they are merged into/override the defaults.\n\n## unsafeWindow\n\n**Type**: `Window`\n\nPortable access to the page's window. This is distinct from the `window` object\nin userscripts, which is an isolated wrapper of the original window (i.e. the\npage's `window` can't see properties of the userscript's `window`).\n\n```javascript\nGMCompat.unsafeWindow.log = GMCompat.unsafeWindow.noop\n```\n\nNote that accessing `unsafeWindow` directly, AKA `window.unsafeWindow`, does\n*not* work in all engines, so this should be used instead if scripts are to be\nrun portably.\n\n## unwrap\n\n**Type**: `\u003cT extends object\u003e(object: T) =\u003e T`\n\nTakes a wrapped object and returns its wrapped value. This is sometimes needed\nwhen working with values transferred from the page to the userscript.\n\n```javascript\nlet result\n\nfunction callback (value) {\n    result = value // may be wrapped (page -\u003e userscript)\n}\n\nconst $callback = GMCompat.export(callback)\n\nGMCompat.unsafeWindow.onResult($callback)\nresult = GMCompat.unwrap(result)\n```\n\n# COMPATIBILITY\n\ngm-compat has been tested on the following engines:\n\n- Greasemonkey (v4.9)\n- Tampermonkey for Firefox (v4.11.6117)\n- Violentmonkey for Firefox (v2.12.7)\n- Violentmonkey for Chrome (v2.12.7)\n\n# DEVELOPMENT\n\n\u003cdetails\u003e\n\n\u003c!-- TOC:ignore --\u003e\n## NPM Scripts\n\nThe following NPM scripts are available:\n\n- build - compile the library and save to the target directory\n- build:doc - generate the README's TOC (table of contents)\n- build:release - compile the library for release and save to the target directory\n- clean - remove the target directory and its contents\n- rebuild - clean the target directory and recompile the library\n\n\u003c/details\u003e\n\n# SEE ALSO\n\n\u003c!-- TOC:ignore --\u003e\n## Libraries\n\n- [gm4-polyfill][] - a polyfill for the GM4 API for GM3-compatible userscript engines\n- [gm-storage][] - an ES6 Map wrapper for the synchronous userscript storage API\n- [UnCommonJs][] - a minimum viable shim for `module.exports`\n\n\u003c!-- TOC:ignore --\u003e\n## Articles\n\n- [MDN - Sharing objects with page scripts][mdn-sharing]\n\n# VERSION\n\n1.1.0\n\n# AUTHOR\n\n[chocolateboy](mailto:chocolate@cpan.org)\n\n# COPYRIGHT AND LICENSE\n\nCopyright © 2020 by chocolateboy.\n\nThis is free software; you can redistribute it and/or modify it under the\nterms of the [Artistic License 2.0](https://www.opensource.org/licenses/artistic-license-2.0.php).\n\n[cloneInto]: https://developer.mozilla.org/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.cloneInto\n[csp]: https://github.com/violentmonkey/violentmonkey/issues/1001\n[exportFunction]: https://developer.mozilla.org/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.exportFunction\n[gm4-polyfill]: https://github.com/greasemonkey/gm4-polyfill\n[gm-storage]: https://www.npmjs.com/package/gm-storage\n[grant-none]: https://github.com/greasemonkey/greasemonkey/issues/3015#issuecomment-436645719\n[jsDelivr]: https://cdn.jsdelivr.net/npm/gm-compat@1.1.0/dist/index.iife.min.js\n[mdn-sharing]: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts\n[UnCommonJS]: https://www.npmjs.com/package/@chocolateboy/uncommonjs\n[unpkg]: https://unpkg.com/gm-compat@1.1.0/dist/index.iife.min.js\n[unsafeWindow]: https://sourceforge.net/p/greasemonkey/wiki/unsafeWindow/\n[xhr#open]: https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/open\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchocolateboy%2Fgm-compat","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchocolateboy%2Fgm-compat","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchocolateboy%2Fgm-compat/lists"}