Content Script Injection: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
remove obsolete content
grammar
Line 1: Line 1:
The previous version of this page may be read [http://wiki.greasespot.net/index.php?title=Content_Script_Injection&oldid=6260 via history].
The previous version of this page may be read [http://wiki.greasespot.net/index.php?title=Content_Script_Injection&oldid=6260 via history].


Since [http://wiki.greasespot.net/Version_history#2.0 Greasemonkey 2.0], scripts which specify <code>@grant none</code> to simply execute in the content page scope.
Since [http://wiki.greasespot.net/Version_history#2.0 Greasemonkey 2.0], scripts which specify <code>@grant none</code> simply execute in the content page scope.
Reading and writing values and calling functions works transparently for interacting with that content scope.
Reading and writing values and calling functions works transparently for interacting with that content scope.



Revision as of 15:55, 23 September 2015

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