簡體   English   中英

Chrome擴展程序:通過注入調用頁面腳本

[英]Chrome-extension: Invoke page script by injection

是否可以將javascript文件注入DOM並立即執行? 我希望在頁面/ DOM中調用javascript函數。 由於孤立的世界,單個內容腳本將無法工作。 使用chrome.tabs.executeScript()需要后台頁面。

簡單示例:
DOM javascript

function sayHello(){
  alert('Hello World');
}

要注入的Javascript文件

console.log('Injection complete. Now calling DOM script.');
sayHello();

這是我最喜歡的兩種方式......

// 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');

此外, 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM