Content Script Injection

From GreaseSpot Wiki
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Warning: The contents of this page are not accurate when used with Greasemonkey 4.0.

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