Content Script Injection

From GreaseSpot Wiki
Revision as of 19:34, 8 April 2011 by Arantius (talk | contribs) (add @require section)
Jump to navigationJump to search

Very similar to the location hack but without either the void() to avoid navigation or escaping issues is the content script injection method. Simply put, Greasemonkey scripts have safe and easy access to modify the DOM of the page, so they can add a <script> tag with any contents.

This is, then, in effect an eval() function that runs code in the content page scope, rather than the Greasemonkey sandbox.

function contentEval(source) {
  // Check for function input.
  if ('function' == typeof source) {
    // Execute this function with no arguments, by adding parentheses.
    // One set around the function, required for valid syntax, and a
    // second empty set calls the surrounded function.
    source = '(' + source + ')();'
  }

  // Create a script node holding this  source code.
  var script = document.createElement('script');
  script.setAttribute("type", "application/javascript");
  script.textContent = source;

  // Insert the script node into the page, so it will run, and immediately
  // remove it to clean up.
  document.body.appendChild(script);
  document.body.removeChild(script);
}

This function can be called with a simple string, which it will run:

contentEval("alert('running in the page')");

Or it can accept a function, which it will turn into a string and run.

contentEval( function() { alert("This function is running in the page scope.") } );

Via @require

Use this function with just one line:

// @require http://userscripts.org/scripts/source/100842.user.js

See Also