Skip to content

Instantly share code, notes, and snippets.

@shesek
Created February 11, 2012 04:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shesek/1796089 to your computer and use it in GitHub Desktop.
Save shesek/1796089 to your computer and use it in GitHub Desktop.
Executing code in the webpage context from Chrome extensions.
inject = (args..., fn) ->
script = document.createElement 'script'
script.innerHTML = """
Array.prototype.pop.call(document.getElementsByTagName('script')).innerText = JSON.stringify(function() {
try { return #{ fn.toString() }.apply(window, #{ JSON.stringify args }); }
catch(e) { return {isException: true, exception: e.toString()}; }
}());
"""
document.body.appendChild script
response = JSON.parse script.innerText
document.body.removeChild script
throw new Error response.exception if response?.isException
response
var inject,
__slice = Array.prototype.slice;
inject = function() {
var args, fn, response, script, _i;
args = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), fn = arguments[_i++];
script = document.createElement('script');
script.innerHTML = "Array.prototype.pop.call(document.getElementsByTagName('script')).innerText = JSON.stringify(function() {\n try { return " + (fn.toString()) + ".apply(window, " + (JSON.stringify(args)) + "); }\n catch(e) { return {isException: true, exception: e.toString()}; }\n}());";
document.body.appendChild(script);
response = JSON.parse(script.innerText);
document.body.removeChild(script);
if (response != null ? response.isException : void 0) {
throw new Error(response.exception);
}
return response;
};
# executes `bar(123)` in the webpage context and saves the return value in `foo`
foo = inject -> bar 123
# executes `bar(baz)` with the `baz` variable from the extension context
foo = inject baz, (baz) -> bar baz
# multiple parameters can be passed like that:
foo = inject baz, qux, (baz, qux) -> bar baz + qux
# or by passing an object:
foo = inject baz: bar, qux: qux, ($) -> bar $.baz + $.qux
# or by using CoffeeScript sugar (desugars to the same as above)
foo = inject {baz, qux}, ($) -> bar $.baz + $.qux
@shesek
Copy link
Author

shesek commented Feb 11, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment