Hier ist meine zwei Lieblings Wege ...
// Executing an anonymous script
function exec(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')();';
document.documentElement.appendChild(script); // run the script
document.documentElement.removeChild(script); // clean up
}
script = function() {
//sayHello();
alert('hello');
}
exec(script);
// Append a script from a file in your extension
function appendScript(scriptFile) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.setAttribute("src", chrome.extension.getURL(scriptFile));
document.documentElement.appendChild(script); // run the script
}
appendScript('someFile.js');
auch zu injizieren chrome.tabs.executeScript()
kann aus einem Popup-Fenster mit einer Browser-/Seitenaktion verwendet werden, und der obige Code funktioniert auch in einem Inhaltsskript.
EDIT
Dank Kommentare von @renocor, hier ist eine Variante der ersten Methode, die Sie Argumente an die injizierten Funktion ....
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);
möglich Duplikat [Aufbau eines Chrome senden können Extension - Inject Code in einer Seite mit einem Content-Skript] (http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script) –