型別 Object
強制 No
範例
"background": {
  "scripts": ["background.js"]
}

background 鍵來引入一個或多個後端腳本,還有一個選擇性的套件後端頁面。

後端腳本是用來放置一些需要維護長期狀態或是進行長期操作的程式碼,它麼的生命週期跟任何網頁或瀏覽器視窗是獨立的。

後端腳本會在套件一被讀取就被讀入,一直到套件被禁用或移除才會卸載。只要你有請求對應的權限你可以在這個腳本裡使用任何擴充套件 APIs。

更多細節,查看套件解析的"後端頁面"章節。

background 鍵是一個物件,可能包含下列二屬性其中之一,兩者都是選擇性的:

"scripts"

一個字串組成的陣列,每個都是 JavaScript 原始碼的路徑。路徑是 manifest.json 檔案自身的相對路徑。這些是會被套件讀取的後端腳本。

腳本共用全局 window

腳本根據陣列裡的順序讀入。

註:Firefox 版本50以前有一個錯誤 當 Firefox 除錯器開啓時,腳本並不總是按照陣列裡的順序讀入。要解決這個錯誤,你可以用 "page" 屬性並且在頁面中透過 <script> 標籤讀入後端腳本。這個錯誤在 Firefox 50 被修正,從那開始腳本總是會依照陣列中的順序讀入。

註: 如果你想要用<script>標籤從遠端取得一個腳本(例如 <script src = "https://code.jquery.com/jquery-1.7.1.min.js">),你必須要修改套件 manifest.json 中的 content_security_policy 鍵。

"page"

如果你指定 "scripts",那麼爲了讓你的腳本執行一個空白頁面會被建立。

如果頁面中需要某些內容,你可以用 "page" 選項定義自己的頁面。

如果你用了這個屬性,你就不能透過 "scripts" 來指定後端腳本。但是你可以像一般的網頁一樣在頁面中引入你自己的腳本。

範例

  "background": {
    "scripts": ["jquery.js", "my-background.js"]
  }

讀取兩個後端腳本。

"background": {
    "page": "my-background.html"
  }

讀取一個自訂的後端頁面。

瀏覽器兼容

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxOperaFirefox for Android
backgroundChrome Full support YesEdge Full support 14Firefox Full support 48Opera Full support YesFirefox Android Full support 48
pageChrome Full support YesEdge Full support 14Firefox Full support 48Opera Full support YesFirefox Android Full support 48
persistentChrome Full support YesEdge Full support 14
Notes
Full support 14
Notes
Notes The 'persistent' property is mandatory.
Firefox Partial support 48
Notes
Partial support 48
Notes
Notes Only persistent pages are supported.
Notes Before version 66, Firefox would log a warning even if the value was set to true.
Opera Full support YesFirefox Android Partial support 48
Notes
Partial support 48
Notes
Notes Only persistent pages are supported.
Notes Before version 66, Firefox would log a warning even if the value was set to true.
scriptsChrome Full support YesEdge Full support 14Firefox Full support 48
Notes
Full support 48
Notes
Notes Before Firefox 50, when the debugger is open, scripts are not always loaded in the order given in the array.
Opera Full support YesFirefox Android Full support 48
Notes
Full support 48
Notes
Notes Before Firefox 50, when the debugger is open, scripts are not always loaded in the order given in the array.

Legend

Full support  
Full support
Partial support  
Partial support
See implementation notes.
See implementation notes.

文件標籤與貢獻者

標籤: 
此頁面的貢獻者: mdnwebdocs-bot, 0711kps
最近更新: mdnwebdocs-bot,