Menu

Metadata_Block

mmartz

Overview

A metadata block is a section of a User script that does not execute any code, but describes the script. The main metadata block is called the UserScript metadata block and typically contains the script name, namespace, description, and Script injection rules.

Any metadata blocks appear in JavaScript comments and may appear anywhere in the top level Greasemonkey code scope of the script, but is usually near the top of the file. It begins with the line:

// ==UserScript==

... and ends with:

// ==/UserScript==

Additional configuration is always between those lines is in the format of:

// @key value

If this metadata block includes a key that Greasemonkey does not understand or tab characters, it will simply be ignored. Code may also occur in-between the header and footer comments. The header comment must always begin on a newline and have no whitespace preceding except for a newline in the text stream. Nested UserScript metadata blocks are not supported. Key names are typically constructed from alphanumeric characters and are case sensitive.

User script hosting sites may utilize a XML styled name prefix to identify the origin of the key. An example of this is prefix:key.

Some sites also support their own evolved metadata block, such as OpenUserJS.org, to minimize collisions with other sites and UserScript engines that define their own standards:

// ==OpenUserJS==

... and ends with:

// ==/OpenUserJS==

Additional site specific configuration is always between those lines is in the format of:

// @key value

Some sites also offer a cross-site compatible metadata block for including library scripts with:

// ==UserLibrary==

... and ends with:

// ==/UserLibrary==

Additional library specific configuration is always between those lines is in the format of:

// @key value

| Other Keys | Examples | Caveats | See Also | Notes

Syntax

// ==UserScript==
// @key value
// ==/UserScript==

// ==OpenUserJS==
// @key value
// ==/OpenUserJS==

Value: Object
Compatibility: Greasemonkey 0.2.5+

Keys

Properties
@name @run-at @require @version
@namespace @include @resource @updateURL
@description @exclude @grant @installURL
@icon @match @unwrap @downloadURL
@author @noframes
@homepageURL
  • All properties are optional.

Properties


name

Blocks: UserScript / UserLibrary
Value: String
Compatibility: Greasemonkey 0.2.5+
Usage:

// @name My Script

Compatibility: Greasemonkey 2.2.0+
Usage:

// @name My Script
// @name:cs    Můj skript
// @name:es-MX Mi guión 
// @name:ru    Мой сценарий
  • The name of the script. This appears in the script manager and monkey menu, and is also used to determine whether to overwrite an old version of a script or to install it separately. If no name is provided, it will be inferred from the file name.
  • If the file name or the @name key exceeds 24 characters the file name will be truncated during installation not including spaces and other special characters. As of Greasemonkey 0.8.0, new scripts will be stored under their own folder name in the gm_scripts folder and also include spaces to underscores conversion and other special characters. The scripts directory is also backed up into a folder called gm_scripts_08bak when migrating to version 0.8.0.
  • When used in the UserLibrary block OpenUserJS.org requires this key to be mirrored in the UserScript block.

namespace

Blocks: UserScript
Value: String
Usage:

// @namespace https://www.example.com/gmscripts
  • The namespace, along with the name, is used to determine whether to overwrite an old version of a script or to install it separately. A script author will usually put all of their scripts under one common namespace, and then assign each script a unique name. If two scripts have the same name, but a different namespace, they can co-exist. However, two scripts of the same name in the same namespace are assumed to be replacements for one another and one will be overwritten by the other.
  • While the namespace is non-semantic, it should be your prefered internet homepage URI according to the W3C standards specification. If no namespace is provided, it is assumed to be the domain from which the script is installed. Since a script can live on various servers or on a local file system, authors may choose to omit this key when publishing on userscripts.org⁸⁰⁸⁰ and let Greasemonkey supply one automatically. If you are creating one locally, authors may choose the URI specification standard of http://localhost for the value as being an anonymous local script.

    • Common String Values

      • Script Host Chosen Namespace via Greasemonkey
        Usage: Omitted @namespace in source userscript file

        • Automatic host to namespace mapping
          Examples:
          • https://userscripts.org/scripts/source/scriptid.user.js maps to
            // @namespace userscripts.org
          • https://example.org/scripts/filename.user.js maps to
            // @namespace example.org
          • http://localhost/scripts/filename.user.js maps to
            // @namespace localhost
      • tag URI
        Usage: "tag:" taggingEntity ":" specific [ "#" fragment ]

        • If a date/time stamp field is omitted, it is assumed to be first item (e.g. 2005 becomes 2005-01-01T00:00:00Z)
          Examples:
          • // @namespace tag:johndoe@example.com,2009:johndoe
          • // @namespace tag:johndoe@example.net,2010-05:johndoe/pathto
          • // @namespace tag:userscripts.org,2005-06-19T23:33:49Z:JohnDoe:DescriptionWithNoSpaces:etc:etc:etc
            See Also: RFC4151
      • userscripts.org (User contributed)
        Usage: id [[ " + " id ], [ " + " id ], ...]
        • An id consists of either a full name, userid or vanityid.
        • Multiple contributor attribution may be notated here by appending the plus symbol and the next id.
          Examples:
          • // @namespace anotherjesse
          • // @namespace userid + vanityid + Firstname Lastname
      • XML URI
        Usage: scheme "://" domain [ "." tld ][ "/" pathto ]
        • See Also: XUL Namespaces
          Examples:
          • // @namespace http://localhost
          • // @namespace http://localhost.localdomain
          • // @namespace https://userscripts.org/users/userid
          • // @namespace https://example.org/pathto/script
    • The NoScript Security Suite add-on currently utilizes namespace filtering, and may sanitize user scripts that are not listed in the XSS white-list section of the options dialog.

description

Blocks: UserScript / UserLibrary
Value: String
Usage:

// @description This script even does the laundry!
  • Just a brief summary of what the script does, to present to the user who is installing it.
  • When used in the UserLibrary block OpenUserJS.org requires this key to be mirrored in the UserScript block.

icon

Blocks: UserScript
Value: URL
Compatibility: Greasemonkey 0.9.0+
Usage:

// @icon https://example.com/icon.png
  • Used to adorn a script with a visual element in the add-ons window.
  • Typically this will be a 32 pixel by 32 pixel image for Firefox 3.x and 48 pixel by 48 pixel image for Firefox 4.×. If the image is larger on the x or the y axis then the respected axes dimension will be reduced to fit.

author

Blocks: UserScript / OpenUserJS
Value: String
Compatibility: Greasemonkey 3.5.0+
Usage:

■ UserScript

// @author Author <Author email> (Author Website)
  • Used in the Add-ons manager more button to give some basic information. Current implementation is to hyperlink to the users @homepageURL. Last value is used and there is no additional UI formatting of the specification at this time e.g. just a string.
  • (Suggest using this key in tandem with @copyright for the UserScript metadata block).

■ OpenUserJS

// @author sizzle
  • Enables collaboration toggle for OpenUserJS metadata block. See @collaborator for adding collaborators.

homepageURL

Blocks: UserScript
Value: URI
Compatibility: Greasemonkey 3.5.0+
Usage:

// @homepageURL https://example.com
  • When used in the UserScript metadata block this link is available to be clicked in the Add-ons manager. Last value is used.
  • There can be any number of @homepageURL keys in a script for multiple homepage urls. The last value is the primary for OpenUserJS.org.
  • OpenUserJs.org allows http, https and mailto protocols.

run-at

Blocks: UserScript
Value: String
Compatibility: Greasemonkey 0.9.8+
Usage:

// @run-at document-end

Default: document-end

  • Intended to control when a script is injected. The legacy behavior is to inject script at the document-end and is suitable for most situations. It is not required to insert this into the metadata block as this key/value pair is the default. However some scripts may benefit from early injection at the document-start.

include

Blocks: UserScript
Value: String
Usage:

// @include https://www.example.com/*

exclude

Blocks: UserScript
Value: String
Usage:

// @exclude https://www.example.com/foo/*

match

Blocks: UserScript
Value: String
Compatibility: Greasemonkey 0.9.8+
Usage:

// @match https://www.example.com/foo/*
  • Refer to Script injection rules. There can be any number of @match rules in a script.
  • Similar to @include, this key provides a more restrictive FQDN value format and is provided solely for Chromium/Chrome compatibility. See syntax here.

noframes

Blocks: UserScript
Value: undefined
Compatibility: Greasemonkey 2.3.0+
Usage:

// @noframes
  • Also referenced as a metadata imperative. This metadata block key property must not include any value after it or it may be ignored altogether.
  • Restricts the injection of a Userscript to be limited to the top level document and never in any frame.

require

Blocks: UserScript
Value: String
Compatibility: Greasemonkey 0.8.0+
Usage:

// @require foo.js
  • There can be any number of @require keys in a script.
  • This metadata block key property may be used to cache a local or remote script into the current user script at installation time. Greasemonkey will not redownload these external dependencies every time the script is executed on a web page specified by @include.
  • As with all metadata values that are stored in config.xml, these are read at install time only. Adding or removing @require entries will have no effect. The script must be reinstalled or the config.xml will need to be modified manually.
  • Script sources may include the scheme of file, http, https or ftp. If no scheme is provided, it is assumed to be the domain from which the script is installed including the full path.
  • Some common JavaScript libraries may be obtained from the Google AJAX Libraries API or YUI.

resource

Blocks: UserScript
Value: String
Compatibility: Greasemonkey 0.8.0+
Usage:

// @resource resourceName https://www.example.com/resource.png
  • There can be any number of @resource keys in a script.
  • While the resourceName is non-semantic, it is suggested that it should be compatible with JavaScript variable naming conventions and XML/CSS naming conventions to help keep things consistent.
  • Each resourceName must have a unique name.
  • This metadata block key property may be used to cache a local or remote resource into the current user script at installation time. Greasemonkey will not redownload these external dependencies every time the script is executed on a web page specified by @include.
  • Resources may include the scheme of file, http, https or ftp. If no scheme is provided, it is assumed to be the domain from which the script is installed including the full path. They may be accessed through GM_getResourceText and GM_getResourceURL respectively.

grant

Blocks: UserScript
Value: String
Compatibility: Greasemonkey 1.0+
Usage:

// @grant GM_addStyle
// @grant GM_deleteValue
// @grant GM_getResourceText
// @grant GM_getResourceURL
// @grant GM_getValue
// @grant GM_listValues
// @grant GM_log
// @grant GM_openInTab
// @grant GM_registerMenuCommand
// @grant GM_setClipboard
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant unsafeWindow

or

// @grant none
  • There can be any number of @grant keys in a script.
  • Greasemonkey 1.0+ now utilizes a metdata block key property to identify which APIs are allowed access in a script. Currently the default is to sniff for these automatically but in future releases // @grant none will be the default. If using // @grant none the code will be assumed to run in the restricted (content scope) namespace.
  • User scripts that run outside of the sandbox with // @grant none may be prone to detection by their respective target sites that they are injected into. There are additional considerations if using a framework like jQuery or YUI in a user script and the target site also uses one of them.
  • Remember to grant access permissions for all resources included in a script. This includes @require and @resource based scripts.

unwrap

Blocks: UserScript
Value: undefined
Compatibility: Greasemonkey 0.8.1 - 0.9.22
Usage:

// @unwrap
  • Also referenced as a metadata imperative. This metadata block key property must not include any value after it or it may be ignored altogether.
  • Removes the anonymous function wrapper around scripts.
  • This key is strongly recommended to only be used for debugging purposes.
  • By default most versions of Greasemonkey automatically encapsulate each script in an anonymous function wrapper. In other words:
  • (function(){ /* script source */ })();
  • Encapsulation of the script prevents name collisions of variables and objects used by XPCNativeWrapper and other objects typically inserted by the browser. If an unwrapped user script uses a reserved object name incorrectly, it will throw an error and script execution will most likely fail. One of the simplest ways to confirm this is to include @unwrap and have a script with a simple variable declaration of var sidebar = "foo";. This will return a script error of Illegal value, and script execution will cease. See also greasemonkey.dejavu.com#108.

version

Blocks: UserScript / UserLibrary
Value: String or Number
Compatibility: Greasemonkey 0.9.0+
Usage:

// @version 0.0.1

updateURL

Blocks: UserScript
Value: URL
Compatibility: Greasemonkey 0.9.12+
Usage:

// @updateURL https://www.example.com/script.user.js

or

// @updateURL https://userscripts.org/scripts/source/scriptid.meta.js
  • This key can always be omitted and the original installation path will be used. This is the default if unspecified or unsupported.
  • The HTTP header, text/x-userscript-meta, should automatically be sent internally to reduce bandwidth and a quicker response by returning only the Metadata Block components supported from the host. Minimal requirement for a successful response is a @version line inside the UserScript metadata block.
  • This key denotes where to check for updates for a @version change. Ideally to prevent DoS and DDoS of any particular server it it strongly recommended to point to a simple metadata block and not the entire source script. This key can always be omitted and the original installation path will be used except when installation occurs from userscripts.org⁸⁰⁸⁰. The user.js portion of the installation URL will automatically converted to the meta.js URL for userscripts.org.
  • If this key is set when publishing to userscripts.org⁸⁰⁸⁰, it is highly recommended to use the meta.js routine URL (See the second usage example above... changing scriptid to your current numerical scriptid). This ensures that other Greasemonkey clones are following userscripts.org guidelines for update checking. This helps to prevent DoS and DDoS attacks for those clones that may implement script updating improperly.

  • NOTE: Some upstream releases of Greasemonkey may not be properly detecting the userscripts.org @updateURL and may be using a special CDN to intercept some of your daily update checks. If you wish to bypass this remote domain by restoring proper usage of the meta.js routine on userscripts.org please use this remote forks repository with the following git commands, or if available in the files section of this project. Remember to manually check for updates in Firefox otherwise next release will automatically be from upstream.:

$ git clone git://git.code.sf.net/p/greasemonkey/code greasemonkey
$ cd greasemonkey
$ git checkout slave
$ ./build.sh official

installURL

Compatibility: Greasemonkey 0.9.12+

downloadURL

Compatibility: Greasemonkey 0.9.14+

Blocks: UserScript
Value: URL
Usage:

// @downloadURL https://www.example.com/script.user.js

or

// @downloadURL https://userscripts.org/scripts/source/scriptid.user.js
  • This key can always be omitted and the original installation path will be used. This is the default if unspecified or unsupported.
  • This key may optionally be set when publishing to userscripts.org⁸⁰⁸⁰. (See the second usage example above... changing scriptid to your current numerical scriptid)
  • NOTE: @downloadURL is a later addition that currently means the same thing as @installURL.

Other Keys

Some Userscripts contain other special keys in the metadata blocks.

These unsupported metadata keys are ignored by the Greasemonkey extension, but can be read by human beings or utilized by other code and site configurations.

Keys

Properties


OpenUserJS.org Userscripts.org⁸⁰⁸⁰ User contributed
@copyright @copyright @uso:unlisted
@license @license @attribution
@homepageURL @uso:script @contributor
@supportURL @uso:version @author
@author @uso:timestamp @major
@collaborator @uso:hash @minor
@unstableMinify @uso:rating @build
@uso:installs
@uso:reviews
@uso:discussions
@uso:fans
  • This is by no means an exhaustive list, nor is it meant to be.

Blocks: UserScript / UserLibrary
Value: String
Usage:

// @copyright Year, Author (Author Website)
  • It is strongly recommended to use this key to identify a scripts copyright author and homepage. Usually a script repository such as userscripts.org⁸⁰⁸⁰ will be able to identify and track copyright via the userid, versions and diffs but it is still suggested to include this for copyright verification purposes.
  • When used in the UserLibrary block OpenUserJS.org requires this key to be mirrored in the UserScript block.
  • Example:
    // @copyright 2009+, John Doe (https://www.example.com/projecthomepage)

licence
license

Blocks: UserScript / UserLibrary
Value: String
Usage:

// @license License Type; License Homepage
  • There can be any number of @license keys in a script for multiple licensing however userscripts.org will only display the first occurrence as the primary.
  • It is strongly recommended to use this key to describe who can use, copy, modify and distribute a script.
  • A list of common open-source licenses can be found at opensource.org. Additionally some sites like OpenUserJS.org utilize the standard SPDX License short identifiers. The OSI License Type SPDX is required to publish any script to OpenUserJS.org.
  • In order to make an assertion on control of distribution of a script, it is important to keep in mind the following definitions:
    • Code (or module) licenses
      These are typically for all Code including binaries, scripts, HTML, XML, and CSS.
    • Content licenses
      These are typically documents such as guides, wikis and static images. The data:image URI scheme is usually considered content unless Code is present.
  • When used in the UserLibrary block OpenUserJS.org requires this key to be mirrored in the UserScript block.
  • Example: (GPL is a Code License and CC is a Content License)
    // @license CC-BY-NC-SA-4.0; https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
    // @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt

supportURL

Blocks: UserScript
Value: URI
Usage:

// @supportURL https://example.com/mysupport
  • There can be any number of @supportURL keys in a script for multiple support urls however openuserjs.org will only display the last value as the primary.
  • OpenUserJs.org allows http, https and mailto protocols.

oujs:author

Status: End of Life 2015 08 24
Value: String
Usage:

// @oujs:author Username
  • OpenUserJS.org allows other users on OUJS to upload or paste modified versions of a script to your account. This key enables this sharing. Only one key of this type is allowed and is the last value supplied.
  • NOTE: This key is no longer supported. Please use @author in the dedicated OpenUserJS block.

oujs:collaborator

Status: End of Life 2015 08 24
Value: String
Usage:

// @oujs:collaborator Username
  • OpenUserJS.org allows other users on OUJS to upload or paste modified versions of your script to your account. This key specifies one other Username to allow access to a script modification. There can be multiple @oujs:collaborator keys defined for larger collaborations.
  • NOTE: This key is no longer supported. Please use @collaborator in the dedicated OpenUserJS block.

uso:script

Blocks: UserScript
Value: String or Number
Usage:

// @uso:script scriptid
  • userscripts.org will dynamically create an ascending numerical value based on the next available script id in the repository.
    NOTE: It is not necessary to define this key in a script as the meta.js routine will automatically return this key/value pairing via a http/https request to https://userscripts.org/scripts/source/scriptid.meta.js

uso:version

Blocks: UserScript
Value: String or Number
Usage:

// @uso:version versionid
  • userscripts.org will dynamically create an ascending numerical value based on the next available version id in the repository.
    NOTE: It is not necessary to define this key in a script as the meta.js routine will automatically return this key/value pairing via a http/https request to https://userscripts.org/scripts/source/scriptid.meta.js

uso:timestamp

Blocks: UserScript
Value: String
Usage:

// @uso:timestamp Wed, 17 Jun 2009 22:50:26 +0000
  • userscripts.org will return the last modified date of the current user script.
    NOTE: It is not necessary to define this key in a script as the meta.js routine will automatically return this key/value pairing via a http/https request to https://userscripts.org/scripts/source/scriptid.meta.js

uso:hash

Blocks: UserScript
Value: String
Usage:

// @uso:hash 30d54f8ba24c0c6ec5710866e9b0839b2066a815
  • userscripts.org will return the sha1_(60)_sum for the current user script.
    NOTE: It is not necessary to define this key in a script as the meta.js routine will automatically return this key/value pairing via a http/https request to https://userscripts.org/scripts/source/scriptid.meta.js

uso:rating

Blocks: UserScript
Value: String or Number
Usage:

// @uso:rating 4.00
  • userscripts.org will return the rating of the current user script. Currently this is an unweighted average of all the peer reviews accurate to two decimal places.
    NOTE: It is not necessary to define this key in a script as the meta.js routine will automatically return this key/value pairing via a http/https request to https://userscripts.org/scripts/source/_scriptid_.meta.js

uso:installs
uso:reviews
uso:discussions
uso:fans

Blocks: UserScript
Value: String or Number
Usage:

// @uso:installs count
// @uso:reviews count
// @uso:discussions count
// @uso:fans count
  • userscripts.org will return the current count for each respective type.
    NOTE: It is not necessary to define these keys in a script as the meta.js routine will automatically return the key/value pairing via a http/https request to https://userscripts.org/scripts/source/scriptid.meta.js

uso:unlisted

Blocks: UserScript
Value: String
Usage:

// @uso:unlisted
  • This is currently a phantom key to self unlist a script used by some update checkers.

attribution

Blocks: UserScript
Value: String
Usage:

// @attribution Attribution Name (Attribution Script Homepage)
  • There can be any number of @attribution keys in a script for multiple attribution support.
  • Attribution may only be used if source @license type is compatible.
  • Example:
// @attribution Jane Doe (https://www.example.com/janedoe/scriptid)
// @attribution Jack Doe (https://www.example.com/jackdoe/scriptid)
// @attribution Jill Doe (https://www.example.com/jilldoe/scriptid)

contributor

Blocks: UserScript
Value: String
Usage:

// @contributor Contributor Name (Contributor Homepage)
  • There can be any number of @contributor keys in a script for multiple contributor support.
  • Example:
    // @contributor Jane Doe (https://www.example.com/janedoe)
    // @contributor Jack Doe (https://www.example.com/jackdoe)
    // @contributor Jill Doe (https://www.example.com/jilldoe)

collaborator

Blocks: OpenUserJS
Value: String
Usage:

// @collaborator Marti
  • Collaborate with another user on the system. Requires OpenUserJS block @author key enabled.
  • Multiple keys are allowed to define multiple collaborators. One username per key.
  • You may announce that you are open to collaboration by setting your own username with one of these keys.

unstableMinify

Blocks: OpenUserJS
Value: String
Usage:

// @unstableMinify A brief technical reason
  • If for some reason minification is known to partially or fully break a Userscript then use this to notify potential installers of technically why.
  • Only one, last in, key is supported
  • If no reason is given the key will be ignored.

major

Blocks: UserScript
Value: Number or String
Usage:

// @major 0
  • Use this to indicate a major release version. Typically if this value is zero than it means pre-release unless specified elsewhere.

minor

Blocks: UserScript
Value: Number or String
Usage:

// @minor 0
  • Use this to indicate a minor release version.

build

Blocks: UserScript
Value: Number or String
Usage:

// @build 1
  • Use this to indicate a build release version.

Examples

| Multiplexing Metadata Blocks | Knowing Your Own Metadata | jQuery require

Core

// ==UserScript==
// @name          My Script
// @namespace     https://www.example.com/gmscripts
// @description   Scripting is fun
// @include       https://www.example.com/*
// @include       https://www.example.org/*
// @exclude       https://www.example.org/foo
// @require       foo.js
// @resource      resourceName1 resource1.png
// @resource      resourceName2 https://www.example.com/resource2.png
// ==/UserScript==

// ==OpenUserJS==
// @author sizzle
// @collaborator Marti
// ==/OpenUserJS==

Multiplexing Metadata Blocks

Some sites require mirroring certain keys in multiple blocks. OpenUserJS.org is an example. Take their "Getting Started with a User Library" example.

Typically one can write this as two separate blocks like this:

// ==UserScript==
// @namespace     https://openuserjs.org/users/username
// @exclude       *
// @name          Getting Started with a User Library
// @description   Showing the current basic and recommended format for a Library script
// @copyright     2017, User Name (https://openuserjs.org/users/username)
// @license       MIT
// @version       0.0.0
// ==/UserScript==

// ==UserLibrary==
// @name          Getting Started with a User Library
// @description   Showing the current basic and recommended format for a Library script
// @copyright     2017, User Name (https://openuserjs.org/users/username)
// @license       MIT
// @version       0.0.0
// ==/UserLibrary==

... however a more convenient method to keep these keys syncronized between the blocks is to do this:

// ==UserScript==
// @namespace     https://openuserjs.org/users/username
// @exclude       *

// ==UserLibrary==
// @name          Getting Started with a User Library
// @description   Showing the current basic and recommended format for a Library script
// @copyright     2017, User Name (https://openuserjs.org/users/username)
// @license       MIT
// @version       0.0.0

// ==/UserScript==

// ==/UserLibrary==

Knowing Your Own Metadata

Logical Control Flow

Methodology


Preparation Restructuring Implementation
Starting a restructure with Function Expression Finishing a restructure
with E4X XMLList
with ES6+ Template Literals
with GM_info

Starting a restructure

Begin by including this L/GPL 3.0 or later code snippet in your source which analyzes the native UserScript Metadata Block and returns a restructured Object in the JSON compatible format.

function parseHeaders(metadataBlock) {
  metadataBlock = metadataBlock.toString();
  var re = /^\/\/ @(\S+)(?:\s+(.*))?/;
  var headers = {};
  var name, prefix, header, key, value;
    var lines = metadataBlock.split(/[\r\n]+/).filter(function (e, i, a) {
      return (e.match(re));
    });
    for (var line in lines) {
      [, name, value] = lines[line].replace(/\s+$/, "").match(re);

      switch (name) {
        case "licence":
          name = "license";
          break;
      }

      [key, prefix] = name.split(/:/).reverse();
      if (key) {
        if (prefix) {
          if (!headers[prefix])
            headers[prefix] = new Object;
          header = headers[prefix];
        }
        else
          header = headers;

        if (header[key]) {
          if (!(header[key] instanceof Array))
            header[key] = new Array(header[key]);
          header[key].push(value || "");
        }
        else
          header[key] = value || "";
      }
    }

    if (headers["license"])
      headers["licence"] = headers["license"];
  return headers;
}

Restructuring with Function Expression

Encase the UserScript Metadata Block in a Function Expression (FE) and pass to the parsing routine.

  • This approach should be cross-browser compatible and is ideally the best choice for restructuring.
  • If a user omits a Greasemonkey supplied key such as @namespace then it will not be reflected in this copy.
  • Remember to change the @uso:script key to match the scriptid hosted on userscripts.org.
  var fileMETA = parseHeaders((function () {

// ==UserScript==
// @name          My Script
// @namespace     https://www.example.com/gmscripts
// @description   Scripting is fun
// @copyright     2009+, John Doe (https://www.example.com/~jdoe)
// @license       GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
// @version       0.0.1
// @include       https://www.example.com/*
// @include       https://www.example.org/*
// @exclude       https://www.example.org/foo
// @require       foo.js
// @resource      resourceName1 resource1.png
// @resource      resourceName2 https://www.example.com/resource2.png
// @grant         GM_log
// @grant         GM_xmlhttpRequest
// @uso:script    scriptid
// ==/UserScript==

  }));

Restructuring with E4X XMLList

Encase the UserScript Metadata Block in a CDATA tag group and pass to the parsing routine.

  • This approach is limited to some Mozilla based browsers.
  • IMPORTANT: E4X has been deprecated and disabled on Mozilla Firefox 17+ versions and is slated to be removed by version 18 release.

  • If a user omits a Greasemonkey supplied key such as @namespace then it will not be reflected in this copy.

  • Remember to change the @uso:script key to match the scriptid hosted on userscripts.org.
  var fileMETA = parseHeaders(<><![CDATA[

// ==UserScript==
// @name          My Script
// @namespace     https://www.example.com/gmscripts
// @description   Scripting is fun
// @copyright     2009+, John Doe (https://www.example.com/~jdoe)
// @license       GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
// @version       0.0.2
// @include       https://www.example.com/*
// @include       https://www.example.org/*
// @exclude       https://www.example.org/foo
// @require       foo.js
// @resource      resourceName1 resource1.png
// @resource      resourceName2 https://www.example.com/resource2.png
// @grant         GM_log
// @grant         GM_xmlhttpRequest
// @uso:script    scriptid
// ==/UserScript==

]]></>.toString()
  );

Restructuring with ES6+ Template Literals

Encase the UserScript Metadata Block in back apostrophes, a.k.a back ticks, to treat it as a multi-line text block.

  • For further reading please refer to Template Literals.
  • This only works in ECMAScript 6 or newer capable browsers as well as UserScript engine support for ES6.
  • If a user omits a Greasemonkey supplied key such as @namespace then it will not be reflected in this copy.
  • Remember to change the @uso:script key to match the scriptid hosted on userscripts.org.
  var fileMETA = parseHeaders(`

// ==UserScript==
// @name          My Script
// @namespace     https://www.example.com/gmscripts
// @description   Scripting is fun
// @copyright     2009+, John Doe (https://www.example.com/~jdoe)
// @license       GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
// @version       0.0.3
// @include       https://www.example.com/*
// @include       https://www.example.org/*
// @exclude       https://www.example.org/foo
// @require       foo.js
// @resource      resourceName1 resource1.png
// @resource      resourceName2 https://www.example.com/resource2.png
// @grant         none
// @uso:script    scriptid
// ==/UserScript==

`
  );

Restructuring with GM_info

The last known native UserScript Metadata Block is available with GM_info. Retrieve this String and pass to the parsing routine.

  • This approach is currently limited to the Greasemonkey add-on and Greasemonkey compatible extensions.
  • GM_info.script may have some scoping issues with certain Object types such as iterating over the @resource values contained in GM_info.script.resources with for…in
  • Remember to change the @uso:script key to match the scriptid hosted on userscripts.org.

// ==UserScript==
// @name          My Script
// @namespace     https://www.example.com/gmscripts
// @description   Scripting is fun
// @copyright     2009+, John Doe (https://www.example.com/~jdoe)
// @license       GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
// @version       0.0.4
// @include       https://www.example.com/*
// @include       https://www.example.org/*
// @exclude       https://www.example.org/foo
// @require       foo.js
// @resource      resourceName1 resource1.png
// @resource      resourceName2 https://www.example.com/resource2.png
// @grant         GM_log
// @grant         GM_xmlhttpRequest
// @uso:script    scriptid
// ==/UserScript==

  var fileMETA = parseHeaders(
    GM_info.scriptMetaStr

    /* These methods are optional and mutually inclusive for tidiness */
    .trim().split(/\n/).map(function (e) { return e.trim(); }).join("\n")
  );

Finishing a restructure

Using GM_xmlhttpRequest to retrieve the meta.js routine from userscripts.org⁸⁰⁸⁰ implement and display name/value pairings to the console.

GM_xmlhttpRequest({
  method:"GET",
  url:"https://userscripts.org/scripts/source/" + fileMETA["uso"]["script"] + ".meta.js",
  headers:{
    "Accept":"text/javascript; charset=UTF-8"
  },
  overrideMimeType:"application/javascript; charset=UTF-8",
  onload:function(response) {
    var httpsMETA = parseHeaders(response.responseText);

    GM_log([
      "\n---------- Local ----------",
      fileMETA["name"] + " version " + fileMETA["version"],
      fileMETA["copyright"],
      fileMETA["license"],
      fileMETA["description"],
      fileMETA["include"],
      fileMETA["exclude"],
      "\n---------- Remote ----------",
      httpsMETA["name"] + " version " + httpsMETA["version"],
      httpsMETA["copyright"],
      httpsMETA["license"],
      httpsMETA["description"],
      httpsMETA["include"],
      httpsMETA["exclude"],
      httpsMETA["uso"]["script"],
      httpsMETA["uso"]["version"],
      httpsMETA["uso"]["timestamp"],
      httpsMETA["uso"]["hash"],
      httpsMETA["uso"]["installs"],
      httpsMETA["uso"]["reviews"],
      httpsMETA["uso"]["rating"],
      httpsMETA["uso"]["discussions"],
      httpsMETA["uso"]["fans"]
    ].join("\n"));
  }
});

jQuery require

  • For neutral documentation sake the latest version url is used, which is currently jQuery Core 1.11.1, however some jQuery maintainers suggest that the latest version should not be used. The meta link has not been updated to the actual latest jQuery Core 1.x series. This is possibly in part due to statistics gathering. Please follow the link for more specifics.
  • Additional specific isolated versions may be found at their CDN including the most recent versions of 1.x and 2.x of the jQuery Core.
  • See also the non-response at jquery/jquery.com#121, and jquery/jquery#2940 with jquery/jquery#2944 as to consideration if frameworks are in the best interest for UserScripts.
// ==UserScript==
// @name          Hello jQuery
// @namespace     https://www.example.com/examples
// @description   jQuery test script
// @include       *
// @require       https://code.jquery.com/jquery-latest.js
// @grant         none
// ==/UserScript==

/* jshint esversion: 5 */
/* globals $, jQuery */

this.$ = this.jQuery = jQuery.noConflict(true);

$(document).ready(function() {
  $("a").click(function() {
    alert('Hello world!');
  });
});

Caveats

See Also

Notes


Related

Wiki: GM_getResourceText
Wiki: GM_getResourceURL
Wiki: GM_info
Wiki: Greasemonkey_Manual:API
Wiki: Greasemonkey_Manual:Creating_Scripts
Wiki: Greasemonkey_Manual:Environment
Wiki: Greasemonkey_Manual:Managing_Scripts
Wiki: Main_Page
Wiki: Metadata_Block
Wiki: Script_injection_rules
Wiki: Scripts_directory
Wiki: User_script
Wiki: Version_history#10
Wiki: XPCNativeWrapper
Wiki: config.xml

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.