What Is the GM_xmlhttpRequest API in Userscripts?

The GM_xmlhttpRequest API is a specialized network function provided by browser userscript managers like Tampermonkey, Violentmonkey, and Greasemonkey. It enables custom JavaScript userscripts to execute cross-origin HTTP requests, bypassing the browser’s native Same-Origin Policy (SOP). This article explores what GM_xmlhttpRequest is, why it is necessary for advanced browser customization, its core parameters, and how to use it securely in your scripts.

The Core Problem: The Same-Origin Policy

When writing standard web scripts, browsers enforce the Same-Origin Policy. This security mechanism restricts web pages from making network requests to a domain different from the one currently serving the page.

If a userscript running on example.com attempts to fetch data from an external API at api.thirdparty.com using native fetch() or standard XMLHttpRequest, the browser will typically block the response due to CORS (Cross-Origin Resource Sharing) restrictions.

How GM_xmlhttpRequest Solves the Problem

Because userscript managers operate with higher privileges than standard web pages, they can expose extended APIs to user scripts. GM_xmlhttpRequest leverages the extension background process to make network calls, allowing your script to:

Basic Syntax and Structure

To use GM_xmlhttpRequest, you must first request permission in the userscript metadata block using the @grant header, along with @connect directives specifying allowed domains.

// ==UserScript==
// @name         External Data Fetcher
// @namespace    http://tampermonkey.net/
// @version      1.0
// @match        https://example.com/*
// @grant        GM_xmlhttpRequest
// @connect      api.github.com
// ==UserScript==

GM_xmlhttpRequest({
    method: "GET",
    url: "https://api.github.com/zen",
    headers: {
        "Accept": "text/plain"
    },
    onload: function(response) {
        console.log("GitHub Zen:", response.responseText);
    },
    onerror: function(error) {
        console.error("Request failed:", error);
    }
});

Key Configuration Options

The function accepts a single configuration object containing parameters similar to standard network APIs:

Security Best Practices

Because GM_xmlhttpRequest elevates network capabilities, improper usage can introduce security vulnerabilities: