chrome.scripting.executescript multiple functions

executeScript 的那個 function name 是OK 的,但其他的 function 並不會同時被一起 inject 進 web page.

解法:
https://developer.chrome.com/docs/extensions/reference/api/scripting

有問題範例:

function getTabId() { ... }
function getUserColor() { ... }

function changeBackgroundColor() {
  document.body.style.backgroundColor = getUserColor();
}

chrome.scripting
    .executeScript({
      target : {tabId : getTabId()},
      func : changeBackgroundColor,
    })
    .then(() => console.log("injected a function"));

使用 File 來 inject 也滿方便:

Files are specified as strings that are paths relative to the extension’s root directory. The following code will inject the file script.js into the main frame of the tab.

function getTabId() { ... }

chrome.scripting
    .executeScript({
      target : {tabId : getTabId()},
      files : [ "script.js" ],
    })
    .then(() => console.log("injected script file"));

取得 inject 結果:

The results of executing JavaScript are passed to the extension. A single result is included per-frame. The main frame is guaranteed to be the first index in the resulting array; all other frames are in a non-deterministic order.

function getTabId() { ... }
function getTitle() { return document.title; }

chrome.scripting
    .executeScript({
      target : {tabId : getTabId(), allFrames : true},
      func : getTitle,
    })
    .then(injectionResults => {
      for (const {frameId, result} of injectionResults) {
        console.log(`Frame ${frameId} result:`, result);
      }
    });

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *