Kim*_*Kim 4 javascript dom code-injection google-chrome-extension
是否可以将javascript文件注入DOM并立即执行?我希望在页面/ DOM中调用javascript函数.由于孤立的世界,单个内容脚本将无法工作.需要使用背景页面chrome.tabs.executeScript().
简单示例:
DOM javascript
function sayHello(){
alert('Hello World');
}
Run Code Online (Sandbox Code Playgroud)
要注入的Javascript文件
console.log('Injection complete. Now calling DOM script.');
sayHello();
Run Code Online (Sandbox Code Playgroud)
这是我最喜欢的两种方式......
// 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');
Run Code Online (Sandbox Code Playgroud)
也chrome.tabs.executeScript()可以从浏览器/页面动作弹出窗口使用,上述代码也可以在内容脚本中使用.
编辑
感谢@renocor的评论,这是第一种方法的变体,它允许您向注入的函数发送参数....
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2626 次 |
| 最近记录: |