Can Userscripts Interact With Host Website APIs?
Userscripts can interact directly with the APIs of the host website
they run on. Depending on the script manager and execution context,
userscripts can access the host page’s global JavaScript objects, invoke
existing frontend API functions, make standard network requests using
fetch or XMLHttpRequest, or use special
extension-level functions to bypass cross-origin restrictions.
Page Context vs. Isolated Context
Browser extensions and userscript managers (such as Tampermonkey or
Violentmonkey) typically execute scripts in an isolated execution
environment. This setup grants the script access to the page’s Document
Object Model (DOM) while keeping its global window object
separate from the website’s native scripts to prevent variable
collisions and security leaks.
To interact with a host website’s internal JavaScript APIs, a userscript must bridge this gap using one of two primary methods:
unsafeWindowObject: Userscript managers provide anunsafeWindowobject that grants direct access to the host page’s nativewindowobject, including global variables, modules, and API helper functions.- DOM Script Injection: A userscript can dynamically
create and append a
<script>tag into the DOM. Code inside this injected tag executes directly within the host page’s main thread and context.
Interacting with Internal and Endpoint APIs
Once access to the host context or network capabilities is established, userscripts interact with host APIs through two main methods:
1. Directly Invoking Native Page Functions
If the host website exposes global functions, state stores (like
Redux or Vuex), or API client objects on the window scope,
a userscript can call these functions directly to perform actions on
behalf of the user.
2. Issuing HTTP Requests
Userscripts can send requests directly to the website’s backend endpoints using:
- Standard
fetch()orXMLHttpRequest: Executing these inside the host context automatically inherits the user’s active session cookies, headers, and authentication tokens. GM_xmlhttpRequest: A specialized API provided by userscript managers that runs outside the browser’s standard CORS restrictions, allowing scripts to communicate with both the host API and third-party services seamlessly.
Security Considerations
While interacting with host APIs enables powerful customizations, it also carries security implications:
- Authentication & Tokens: Scripts executing within the page context inherit the logged-in user’s privileges, meaning untrusted userscripts could perform unauthorized actions.
- Content Security Policy (CSP): Strict host CSP rules may block inline script injection, requiring developers to rely on built-in userscript manager privileges rather than DOM manipulation.