Content Script Injection

From GreaseSpot Wiki
Revision as of 11:55, 23 September 2015 by Arantius (talk | contribs) (grammar)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The previous version of this page may be read via history.

Since Greasemonkey 2.0, scripts which specify @grant none simply execute in the content page scope. Reading and writing values and calling functions works transparently for interacting with that content scope.

For scripts which @grant any privileged APIs, these methods are provided in a privileged scope which is intentionally isolated from the content page. The same functionality is available by calling window.eval() to explicitly target the content window scope for execution. (Note that a bare eval() executes in the script scope.)

// ==UserScript==
// @name        Content Script Example, grant none
// @grant       none
// ==/UserScript==

// Because I am a "@grant none" script, I operate right in the content scope.
// I can call functions defined by the page with no problems.
var result = functionFromContentScope();

// Similarly, I can export values or functions to that scope for it to call.
window.someVariable = 'someValue';
// ==UserScript==
// @name        Content Script Example, privileged grant
// @grant       GM_log
// ==/UserScript==

// Because I am *not* a "@grant none" script, I operate in my own private,
// privileged scope.  I can call functions defined by the page only by
// explicitly referencing the window:
var result = window.eval('functionFromContentScope();')

// Similarly, I can export values or functions to that scope for it to call.
window.eval("window.someVariable = 'someValue';");

See Also