contentScripts.register()

使用此函式來註冊一個或多個內容指令碼。

它接受一個引數,該引數是一個物件,其屬性與 content_scripts manifest 鍵中提供的物件相似(但請注意,content_scripts 是一個物件陣列,而 register() 的引數是一個物件)。

擴充套件必須具有 contentScriptOptions 中模式的適當 主機許可權,否則 API 呼叫將被拒絕。

語法

js
let registering = browser.contentScripts.register(
  contentScriptOptions       // object
)

引數

contentScriptOptions

object。一個 RegisteredContentScriptOptions 物件,表示要註冊的內容指令碼。其語法與 content_scripts manifest 鍵陣列中的物件相似。區別在於:

  • 屬性名使用 駝峰式命名,而不是下劃線(蛇形命名)— 例如,excludeMatches,而不是 exclude_matches
  • jscss 屬性允許你註冊字串以及 URL,因此它們的語法必須區分這些型別。

RegisteredContentScriptOptions 物件具有以下屬性:

allFrames 可選

content_scripts 鍵中的 all_frames 相同。

cookieStoreId 可選

一個字串或字串陣列。在屬於一個或多個 cookie 儲存 ID 的標籤頁中註冊內容指令碼。這使得指令碼可以為所有預設或非情境身份標籤頁、私密瀏覽標籤頁(如果 擴充套件在私密瀏覽中啟用)、情境身份 的標籤頁,或這些的組合進行註冊。有關更多資訊,請參閱 處理情境身份

css 可選

一個物件陣列。每個物件都有一個名為 file 的屬性,該屬性是一個以擴充套件的 manifest.json 開始並指向要註冊的 CSS 檔案的 URL,或者有一個名為 code 的屬性,該屬性是要註冊的 CSS 程式碼。

cssOrigin 可選

string。注入樣式的來源,可以是 "user",將 CSS 新增為使用者樣式表,或者 "author",將其新增為作者樣式表。預設為 "author"。此屬性不區分大小寫。

excludeGlobs 可選

content_scripts 鍵中的 exclude_globs 相同。

excludeMatches 可選

content_scripts 鍵中的 exclude_matches 相同。

includeGlobs 可選

content_scripts 鍵中的 include_globs 相同。

js 可選

一個物件陣列。每個物件都有一個名為 file 的屬性,該屬性是一個以擴充套件的 manifest.json 開始並指向要註冊的 JavaScript 檔案的 URL,或者有一個名為 code 的屬性,該屬性是要註冊的 JavaScript 程式碼。

matchAboutBlank 可選

content_scripts 鍵中的 match_about_blank 相同。

matchOriginAsFallback 可選

content_scripts 鍵中的 match_origin_as_fallback 相同。

matches

content_scripts 鍵中的 matches 相同。

runAt 可選

content_scripts 鍵中的 run_at 相同。

world 可選

指令碼執行的環境。與 content_scripts 鍵中的 world 相同。

返回值

一個 Promise,它將用一個 contentScripts.RegisteredContentScript 物件fulfilled,你可以使用該物件來取消註冊內容指令碼。

目前,當相關的擴充套件頁面(從中註冊了內容指令碼)解除安裝時,內容指令碼就會被取消註冊,因此你應該從一個持續時間至少與你希望內容指令碼保持註冊狀態一樣長的擴充套件頁面註冊內容指令碼。

示例

此示例為所有 .org URL 註冊了 defaultCode 內容指令碼。

js
const defaultHosts = "*://*.org/*";
const defaultCode =
  "document.body.innerHTML = '<h1>This page has been eaten<h1>'";

async function register(hosts, code) {
  return await browser.contentScripts.register({
    matches: [hosts],
    js: [{ code }],
    runAt: "document_idle",
  });
}

let registered = register(defaultHosts, defaultCode);

此程式碼註冊了 content_scripts/example.js 檔案。

js
const scriptObj = await browser.contentScripts.register({
  js: [{ file: "/content_scripts/example.js" }],
  matches: ["<all_urls>"],
  allFrames: true,
  runAt: "document_start",
});

擴充套件程式示例

瀏覽器相容性