Content Scope Runner

From GreaseSpot Wiki
Revision as of 16:41, 26 September 2010 by Ecmanaut (talk | contribs) (Noted suggestion to change the __PAGE_SCOPE_RUN__ identifier.)
Jump to navigationJump to search

An extension of the Content Script Injection technique, this snippet automatically runs the entire user script in the content scope.

if ('undefined' == typeof __PAGE_SCOPE_RUN__) {
  (function page_scope_runner() {
    // If we're _not_ already running in the page, grab the full source
    // of this script.
    var my_src = "(" + page_scope_runner.caller.toString() + ")();";

    // Create a script node holding this script, plus a marker that lets us
    // know we are running in the page scope (not the Greasemonkey sandbox).
    // Note that we are intentionally *not* scope-wrapping here.
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
        "data:,"+escape("var __PAGE_SCOPE_RUN__ = true;\n" + my_src));

    // Insert the script node into the page, so it will run, and immediately
    // remove it to clean up.  Use setTimeout to force execution "outside" of
    // the user script scope completely.
    setTimeout(function() {
        }, 0);

  // Stop running, because we know Greasemonkey actually runs us in
  // an anonymous wrapper.

As soon as execution reaches this code, the entire script will be injected into the page and re-run. Thus you need not worry about any of the security restrictions from XPCNativeWrappers in the Greasemonkey sandbox. You also will, of course, not have access to any of the APIs.


  • This code must not be wrapped in a function, or the return will fail to work. It may be wrapped in a conditional.
  • Any code before (and including) this block will be run twice: Once in GreaseMonkey context, once in page context.
  • Any code after this block will only be run once, in the page context.
  • You should change __PAGE_SCOPE_RUN__ to another identifier not present in web pages you run on and unique to your script, or only one of potentially multiple scripts the user has installed running on the current page will actually run.


The code block first checks to see if it is being run inside the page by looking for a marker it knows about. If the marker is not present, the block creates and injects a script element that starts by setting the aforementioned marker variable and finishes by executing the text of the user script. Finally, the block calls return, ending execution.


Since it must run before the rest of the script, this snipped functions best as the first @require. Try it by adding this line as the first @require in the Metadata Block:

// @require