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…' |
(No difference)
|
Revision as of 18:13, 4 February 2010
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.") } );