Content Script Injection: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
(Created page with 'Very similar to the location hack but without either the <code>void()</code> to avoid navigation or escaping issues is the content script injection method. Simply put, Grease…')
 
(add @require section)
Line 33: Line 33:


<pre class='sample'>contentEval( function() { alert("This function is running in the page scope.") } );</pre>
<pre class='sample'>contentEval( function() { alert("This function is running in the page scope.") } );</pre>
== Via @require ==
Use this function with just one line:
<pre class='sample'>// @require http://userscripts.org/scripts/source/100842.user.js</pre>


== See Also ==
== See Also ==

Revision as of 19:34, 8 April 2011

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