@grant

From GreaseSpot Wiki
Revision as of 14:27, 28 June 2012 by Arantius (talk | contribs)
Jump to navigationJump to search

This page describes features that are currently unreleased.

Greasemonkey 1.0 adds a special Metadata Block imperative: @grant. As of version 1.0:

  • If a script does not specify any @grant values, Greasemonkey will attempt to auto-detect the right settings.
  • If a script specifies any values (or they have been auto detected), then it will be provided with only those API methods that it declares.
    • The valid values are the names of those GM_ prefixed values that you wish your script to be granted access to.
  • Otherwise the script will be granted no special API privileges, and thus run without the security constraints Greasemonkey scripts have traditionally had. If you want your script to operate in this mode, you should explicitly declare @grant none.

Examples

It's common for scripts (over half when last counted) not to use any special APIs at all. For such scripts, explicitly asking to be granted no special privileges means that the script will execute directly in the content page. This means no security sandbox, and none of its limitations, so accessing variables in the page just works, calling functions and reading their results also just works. To do so, simply:

// ==UserScript==
// @name        Grant None Example
// @include     http*
// @grant       none
// ==/UserScript==

console.log('This script grants no special privileges, so it runs without security limitations.');

If you do use one of Greasemonkey's APIs, you should explicitly ask for it to be granted to your script:

// ==UserScript==
// @name        Grant Some Example
// @include     http*
// @grant       GM_getValue
// @grant       GM_setValue
// ==/UserScript==

var counter = GM_getValue('counter', 0);
console.log('This script has been run ' + counter + ' times.');
GM_setValue('counter', ++counter);

In this case, the script is asking to be granted access to both GM_getValue and GM_setValue, one on each @grant line. Specify the name of any Greasemonkey API to be granted access to it. (All scripts always get GM_info without specifically requesting it.) Temporarily, this would also work:

// ==UserScript==
// @name        Grant Legacy Example
// @include     http*
// ==/UserScript==

var counter = GM_getValue('counter', 0);
console.log('This script has been run ' + counter + ' times.');
GM_setValue('counter', ++counter);

This example will work in Greasemonkey version 1.0. When there are no @grant lines, Greasemonkey tries to detect which APIs are being used, and act as if those @grant lines had been specified. This detection may fail in certain cases, especially when eval() is used.

All scripts written before @grant should continue to work because of this, but you should change your scripts to specify @grant at your earliest convenience, so they don't break in the future.