Content Script Injection: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
(grammar)
(Update for 4.0)
 
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].
<div style="border: 3px dotted; color: red; font-size: 1.2em; padding: 0.5em; margin: 1em; text-align: center">
 
Warning: The contents of this page are not accurate when used with Greasemonkey 4.0.
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.
</div>
Reading and writing values and calling functions works transparently for interacting with that content scope.


For scripts which <code>@grant</code> any privileged APIs, these methods are provided in a privileged scope which is intentionally isolated from the content page.
For scripts which <code>@grant</code> any privileged APIs, these methods are provided in a privileged scope which is intentionally isolated from the content page.

Latest revision as of 16:28, 3 November 2017

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