GM APIs Reference

Complete reference for all Greasemonkey APIs supported by CodeTweak with practical examples and best practices.

Remember: You must enable each GM API in the script editor's "GM API Access" section before using it in your code.

Storage & Data APIs

GM_setValue
Storage

Stores a value that persists across page loads and browser sessions.

GM_setValue('key', value)
Parameter Type Description
key string Unique identifier for the stored value
value any Value to store (string, number, boolean, object)

Example Usage:

// Store different types of data
GM_setValue('username', 'john_doe');
GM_setValue('score', 1250);
GM_setValue('settings', {theme: 'dark', notifications: true});
GM_setValue('lastVisit', new Date().toISOString());
GM_getValue
Storage

Retrieves a previously stored value, with optional default fallback.

GM_getValue('key', defaultValue)
Parameter Type Description
key string Key of the value to retrieve
defaultValue any Value returned if key doesn't exist

Example Usage:

// Get stored values with defaults
const username = GM_getValue('username', 'anonymous');
const score = GM_getValue('score', 0);
const settings = GM_getValue('settings', {theme: 'light'});

// Use the retrieved values
console.log(`Welcome back, ${username}! Your score: ${score}`);
GM_deleteValue
Storage

Removes a stored value permanently.

GM_deleteValue('key')

Example Usage:

// Clear user data
GM_deleteValue('username');
GM_deleteValue('score');

// Clear all data on reset
function resetUserData() {
    GM_deleteValue('settings');
    GM_deleteValue('resetRequested');
}
GM_listValues
Storage

Returns an array of all stored keys for this script.

GM_listValues()

Example Usage:

// List all stored keys
const keys = GM_listValues();
console.log('Stored keys:', keys);

// Export all data
const exportData = {};
keys.forEach(key => {
    exportData[key] = GM_getValue(key);
});
console.log('Export data:', exportData);

Browser & UI APIs

GM_openInTab
Browser

Opens a URL in a new browser tab with optional configuration.

GM_openInTab(url, options)
Parameter Type Description
url string URL to open
options object Configuration object (optional)
options.active boolean Whether to focus the new tab

Example Usage:

// Open in background tab
GM_openInTab('https://example.com', {active: false});

// Open in focused tab
GM_openInTab('https://github.com', {active: true});

// Simple usage
GM_openInTab('https://google.com');
GM_notification
UI

Displays a desktop notification to the user.

GM_notification(options)
Parameter Type Description
options.text string Notification message
options.title string Notification title (optional)
options.image string Icon URL (optional)
options.onclick function Click handler (optional)

Example Usage:

// Simple notification
GM_notification({
    text: 'Script executed successfully!',
    title: 'CodeTweak'
});

// Advanced notification with callback
GM_notification({
    text: 'New message received',
    title: 'Chat App',
    image: 'https://example.com/icon.png',
    onclick: function() {
        window.focus();
        console.log('Notification clicked');
    }
});
GM_addStyle
UI

Injects CSS styles into the current page.

GM_addStyle(css)

Example Usage:

// Add custom styles
GM_addStyle(`
    .my-custom-class {
        background: #f0f0f0;
        padding: 10px;
        border-radius: 5px;
    }
    .highlight {
        background: yellow;
        font-weight: bold;
    }
`);

// Apply styles to existing elements
document.querySelectorAll('.important').forEach(el => {
    el.classList.add('highlight');
});
GM_addElement
UI

Creates and appends a new DOM element with specified attributes.

GM_addElement(parent, tag, attributes)
Parameter Type Description
parent Element Parent element to append to
tag string HTML tag name
attributes object Element attributes (optional)

Example Usage:

// Add a button to the page
const button = GM_addElement(document.body, 'button', {
    textContent: 'Click Me!',
    onclick: () => alert('Button clicked!')
});

// Add a styled container
const container = GM_addElement(document.body, 'div', {
    id: 'my-container',
    style: 'position: fixed; top: 10px; right: 10px; z-index: 9999;'
});

Network & Resources APIs

GM_xmlhttpRequest
Network

Makes cross-origin HTTP requests that bypass CORS restrictions.

GM_xmlhttpRequest(options)
Parameter Type Description
options.method string HTTP method (GET, POST, etc.)
options.url string Request URL
options.headers object Request headers (optional)
options.data string Request body (optional)
options.onload function Success callback
options.onerror function Error callback

Example Usage:

// GET request
GM_xmlhttpRequest({
    method: 'GET',
    url: 'https://api.example.com/data',
    headers: {
        'User-Agent': 'CodeTweak Script',
        'Accept': 'application/json'
    },
    onload: function(response) {
        console.log('Status:', response.status);
        console.log('Response:', response.responseText);
    }
});

// POST request with data
GM_xmlhttpRequest({
    method: 'POST',
    url: 'https://api.example.com/submit',
    headers: {
        'Content-Type': 'application/json'
    },
    data: JSON.stringify({message: 'Hello World'}),
    onload: function(response) {
        console.log('Response:', response.responseText);
    }
});
GM_getResourceText
Resources

Retrieves the content of a bundled resource as text.

GM_getResourceText('resourceName')
Setup Required: Resources must be defined in the editor's "Script Resources" section before use.

Example Usage:

// Get CSS resource and inject it
const customCSS = GM_getResourceText('myStyles');
GM_addStyle(customCSS);

// Get JSON config file
const configText = GM_getResourceText('config');
const config = JSON.parse(configText);
console.log('Config loaded:', config);
GM_setClipboard
System

Copies text to the system clipboard.

GM_setClipboard(text, type)
Parameter Type Description
text string Text to copy to clipboard
type string MIME type (optional, defaults to 'text/plain')

Example Usage:

// Copy simple text
GM_setClipboard('Hello, World!');

// Copy formatted data
const data = {name: 'John', age: 30};
GM_setClipboard(JSON.stringify(data, null, 2));

// Copy with specific MIME type
GM_setClipboard('

Hello

', 'text/html');
Security Notes:
  • Validate data from GM_getValue before use
  • Be cautious with GM_xmlhttpRequest to untrusted URLs
  • Sanitize content before using GM_addStyle or GM_addElement