Skip to content

Instantly share code, notes, and snippets.

@PAEz
Last active December 16, 2015 11:18
Show Gist options
  • Save PAEz/5426120 to your computer and use it in GitHub Desktop.
Save PAEz/5426120 to your computer and use it in GitHub Desktop.
Attach a function to a page from a content script and execute it with arguments.
function exec(fn) {
var args = '';
if (arguments.length > 1) {
for (var i = 1, end = arguments.length - 2; i <= end; i++) {
args += typeof arguments[i]=='function' ? arguments[i] : JSON.stringify(arguments[i]) + ', ';
}
args += typeof arguments[i]=='function' ? arguments[arguments.length - 1] : JSON.stringify(arguments[arguments.length - 1]);
}
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')(' + args + ');';
document.documentElement.appendChild(script); // run the script
document.documentElement.removeChild(script); // clean up
}
script = function(what, huh, nah, yeah) {
console.debug(arguments);
console.debug('what=', what);
console.debug('huh=', huh);
console.debug('nah=', nah);
console.debug('yeah=', yeah);
if (typeof yeah=='function') yeah();
}
exec(script, 'meh', ['bleh'], {
a: {
b: 0
}
}, function(){
alert('hi');
});
console.debug('No arguments');
exec(script);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment