內容指令碼是在網頁環境中執行的檔案,有了標準文件物件模型 (DOM),他們就能讀取瀏覽器造訪的網頁詳細資料、進行變更,並將資訊傳送至父項擴充功能。
瞭解內容指令碼功能
內容指令碼宣告擴充功能為可透過網路存取的資源後,就能存取擴充功能檔案。並可直接存取下列擴充功能 API:
dom
i18n
storage
runtime.connect()
runtime.getManifest()
runtime.getURL()
runtime.id
runtime.onConnect
runtime.onMessage
runtime.sendMessage()
內容指令碼無法直接存取其他 API。但他們可以與擴充功能的其他部分互換訊息,間接存取這些郵件。
在隔離環境中工作
內容指令碼存在於獨立環境中,能讓內容指令碼對 JavaScript 環境進行變更,而不會與網頁或其他擴充功能的內容指令碼發生衝突。
擴充功能可能會在網頁上執行,其程式碼如下方範例所示。
webPage.html
<html>
<button id="mybutton">click me</button>
<script>
var greeting = "hello, ";
var button = document.getElementById("mybutton");
button.person_name = "Bob";
button.addEventListener(
"click", () => alert(greeting + button.person_name + "."), false);
</script>
</html>
該擴充功能可以使用「插入指令碼」一節所述的其中一種技術,插入下列內容指令碼。
content-script.js
var greeting = "hola, ";
var button = document.getElementById("mybutton");
button.person_name = "Roberto";
button.addEventListener(
"click", () => alert(greeting + button.person_name + "."), false);
經過變更後,使用者點選按鈕時,系統會依序顯示兩則快訊。
插入指令碼
內容指令碼可以以靜態方式宣告、透過動態方式宣告,或透過程式輔助方式插入。
使用靜態宣告插入
針對應在一組已知網頁上自動執行的指令碼,使用 manifest.json 中的靜態內容指令碼宣告。
系統會將靜態宣告的指令碼註冊在資訊清單中的 "content_scripts"
鍵下方。可包含 JavaScript 檔案和/或 CSS 檔案。所有自動執行內容指令碼都必須指定比對模式。
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.nytimes.com/*"],
"css": ["my-styles.css"],
"js": ["content-script.js"]
}
],
...
}
名稱 | 類型 | 說明 |
---|---|---|
matches |
字串陣列 | 必要。指定要將這個內容指令碼插入哪些網頁。如要進一步瞭解這些字串的語法,請參閱比對模式和「比對模式和 glob」一文,進一步瞭解如何排除網址。 |
css |
字串陣列 | 選用。要插入相符頁面的 CSS 檔案清單。系統會按照出現在此陣列中的順序插入這些標記,在為頁面建構或顯示任何 DOM 之前。 |
js |
|
選用。要插入相符網頁的 JavaScript 檔案清單。系統會按照此陣列中的顯示順序插入檔案。這份清單中的每個字串都必須包含擴充功能根目錄中資源的相對路徑。系統會自動移除開頭的斜線 (`/`)。 |
run_at |
RunAt | 選用。指定將指令碼插入網頁的時機。預設值為 document_idle 。 |
match_about_blank |
boolean | 選用。是否應將指令碼插入 about:blank 影格,當中的父項或開啟頁框與 matches 中宣告的模式相符。預設值為 false。 |
match_origin_as_fallback |
boolean |
選用。指令碼是否應插入由相符來源建立的影格,但其網址或來源不得與模式直接相符。包括具有不同配置 (例如 about: 、data: 、blob: 和 filesystem: ) 的影格。另請參閱「插入相關影格」。 |
world |
ExecutionWorld |
選用。指令碼在 JavaScript 環境中執行的情況。預設值為 ISOLATED 。另請參閱「在隔離環境中工作」。 |
使用動態宣告插入
如果內容指令碼的比對模式不明,或內容指令碼不應一律插入已知主機,動態內容指令碼就非常實用。
在 Chrome 96 版中引入,動態宣告與靜態宣告類似,但內容指令碼物件是透過 chrome.scripting
命名空間 (而非 manifest.json) 中的方法在 Chrome 註冊。Scripting API 也可讓擴充功能開發人員:
和靜態宣告一樣,動態宣告可包含 JavaScript 檔案和/或 CSS 檔案。
service-worker.js
chrome.scripting
.registerContentScripts([{
id: "session-script",
js: ["content.js"],
persistAcrossSessions: false,
matches: ["*://example.com/*"],
runAt: "document_start",
}])
.then(() => console.log("registration complete"))
.catch((err) => console.warn("unexpected error", err))
service-worker.js
chrome.scripting
.updateContentScripts([{
id: "session-script",
excludeMatches: ["*://admin.example.com/*"],
}])
.then(() => console.log("registration updated"));
service-worker.js
chrome.scripting
.getRegisteredContentScripts()
.then(scripts => console.log("registered content scripts", scripts));
service-worker.js
chrome.scripting
.unregisterContentScripts({ ids: ["session-script"] })
.then(() => console.log("un-registration complete"));
透過程式輔助插入
針對需要因應事件或特定情況執行的內容指令碼,使用程式輔助插入。
如要透過程式插入內容指令碼,您的擴充功能需要針對要插入指令碼的網頁,具備主機權限。您可以在擴充功能資訊清單中要求主機權限,或暫時使用 "activeTab"
,藉此授予主機權限。
以下是 ActiveTab 擴充功能的不同版本。
manifest.json:
{
"name": "My extension",
...
"permissions": [
"activeTab",
"scripting"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "Action Button"
}
}
內容指令碼可以插入為檔案。
content-script.js
document.body.style.backgroundColor = "orange";
service-worker.js:
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["content-script.js"]
});
});
此外,函式主體也可以插入及執行做為內容指令碼。
service-worker.js:
function injectedFunction() {
document.body.style.backgroundColor = "orange";
}
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target : {tabId : tab.id},
func : injectedFunction,
});
});
請注意,插入的函式是 chrome.scripting.executeScript()
呼叫中參照的函式副本,而非原始函式本身。因此,函式的主體必須為獨立的;參照函式外的變數會導致內容指令碼擲回 ReferenceError
。
插入為函式時,您也可以將引數傳遞給函式。
service-worker.js
function injectedFunction(color) {
document.body.style.backgroundColor = color;
}
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target : {tabId : tab.id},
func : injectedFunction,
args : [ "orange" ],
});
});
排除相符項目和 glob
如要自訂指定的網頁比對方法,請在宣告式註冊中加入下列欄位。
名稱 | 類型 | 說明 |
---|---|---|
exclude_matches |
字串陣列 | 選用。排除會插入此內容指令碼的網頁。如要進一步瞭解這些字串的語法,請參閱比對模式。 |
include_globs |
字串陣列 | 選用。會在 matches 之後套用,僅納入與這個 glob 相符的網址。用於模擬「@include 」希臘關鍵字。 |
exclude_globs |
字串陣列 | 選用。會在 matches 之後套用,以排除與這個 glob 相符的網址。用來模擬 Greasemonkey 關鍵字 @exclude 。 |
如果同時符合以下兩項條件,系統就會將內容指令碼插入網頁:
- 這個網址的網址符合任何
matches
模式和任何include_globs
模式。 - 網址也不符合
exclude_matches
或exclude_globs
模式。由於matches
是必要屬性,因此exclude_matches
、include_globs
和exclude_globs
只能用於限制哪些網頁會受到影響。
下列擴充功能會將內容指令碼插入 https://www.nytimes.com/health
,但不會插入 https://www.nytimes.com/business
。
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.nytimes.com/*"],
"exclude_matches": ["*://*/*business*"],
"js": ["contentScript.js"]
}
],
...
}
service-worker.js
chrome.scripting.registerContentScripts([{
id : "test",
matches : [ "https://*.nytimes.com/*" ],
excludeMatches : [ "*://*/*business*" ],
js : [ "contentScript.js" ],
}]);
Glob 屬性的語法與比對模式不同,且語法更靈活。可接受的 glob 字串是可能包含「萬用字元」星號和問號的網址。星號 (*
) 會比對任何長度的字串,包括空字串,而問號 (?
) 則會比對任何單一字元。
例如,glob https://???.example.com/foo/\*
會比對下列任一項目:
https://www.example.com/foo/bar
https://the.example.com/foo/
但是,它「不」與下列字串相符:
https://my.example.com/foo/bar
https://example.com/foo/
https://www.example.com/foo
這項擴充功能會將內容指令碼插入 https://www.nytimes.com/arts/index.html
和 https://www.nytimes.com/jobs/index.htm*
,但不會插入 https://www.nytimes.com/sports/index.html
:
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.nytimes.com/*"],
"include_globs": ["*nytimes.com/???s/*"],
"js": ["contentScript.js"]
}
],
...
}
這項擴充功能會將內容指令碼插入 https://history.nytimes.com
和 https://.nytimes.com/history
,但不會插入 https://science.nytimes.com
或 https://www.nytimes.com/science
:
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.nytimes.com/*"],
"exclude_globs": ["*science*"],
"js": ["contentScript.js"]
}
],
...
}
加入單一、全部或部分,即可達成正確範圍。
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.nytimes.com/*"],
"exclude_matches": ["*://*/*business*"],
"include_globs": ["*nytimes.com/???s/*"],
"exclude_globs": ["*science*"],
"js": ["contentScript.js"]
}
],
...
}
執行時間
run_at
欄位可控制 JavaScript 檔案插入網頁的時機。偏好且預設值為 "document_idle"
。如要瞭解其他可能的值,請參閱 RunAt 類型。
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.nytimes.com/*"],
"run_at": "document_idle",
"js": ["contentScript.js"]
}
],
...
}
service-worker.js
chrome.scripting.registerContentScripts([{
id : "test",
matches : [ "https://*.nytimes.com/*" ],
runAt : "document_idle",
js : [ "contentScript.js" ],
}]);
名稱 | 類型 | 說明 |
---|---|---|
document_idle |
字串 | 建議採用。請盡可能使用 "document_idle" 。瀏覽器會選擇在 "document_end" 之間到 window.onload 事件觸發後,立即插入指令碼的時間。確切插入時間點取決於文件的複雜程度和載入時間,且已針對網頁載入速度進行最佳化。在 "document_idle" 執行的內容指令碼不需要監聽 window.onload 事件,確保會在 DOM 完成後執行。如果指令碼必須在 window.onload 之後執行,擴充功能可以使用 document.readyState 屬性檢查 onload 是否已觸發。 |
document_start |
字串 | 系統會在 css 中的任何檔案之後,在建構其他 DOM 或執行任何其他指令碼前,插入指令碼。 |
document_end |
字串 | 指令碼會在 DOM 完成後立即插入,但在載入圖片和頁框等子資源之前。 |
指定影格
"all_frames"
欄位可讓擴充功能指定是否應將 JavaScript 和 CSS 檔案插入符合指定網址規定的所有頁框,或只插入分頁中最上方的頁框。
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.nytimes.com/*"],
"all_frames": true,
"js": ["contentScript.js"]
}
],
...
}
service-worker.js
chrome.scripting.registerContentScripts([{
id: "test",
matches : [ "https://*.nytimes.com/*" ],
allFrames : true,
js : [ "contentScript.js" ],
}]);
名稱 | 類型 | 說明 |
---|---|---|
all_frames |
boolean | 選用。預設值為 false ,表示只比對頂層頁框。如果指定 true ,則所有頁框都會插入,即使其並非分頁中最上層的頁框也是如此。系統會根據網址規定分別檢查每個頁框。如果不符合網址規定,則不會插入子頁框。 |
插入相關影格
擴充功能可能會在與相符影格相關的影格中執行指令碼,但因為兩者不相容。常見的情況是,網址頁框是由相符影格建立,但其網址本身與指令碼指定的模式不符。
當擴充功能要在網址含有 about:
、data:
、blob:
和 filesystem:
配置的網址中插入頁框時,就會發生這種情況。在這種情況下,網址會不符合內容指令碼的模式 (而且,在 about:
和 data:
中,甚至完全不在網址中加入上層網址或來源,就像在 about:blank
或 data:text/html,<html>Hello, World!</html>
中一樣)。不過,這些頁框仍可與建立頁框相關聯。
如要插入這些影格,擴充功能可以在資訊清單的內容指令碼規格中指定 "match_origin_as_fallback"
屬性。
manifest.json
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["https://*.google.com/*"],
"match_origin_as_fallback": true,
"js": ["contentScript.js"]
}
],
...
}
指定且設為 true
時,Chrome 會查看影格啟動者的來源,以判斷影格是否相符,而不是影格本身的網址。請注意,這也可能與目標影格的「來源」不同 (例如data:
網址的來源為空值)。
影格的啟動器是建立或瀏覽目標影格的影格。雖然這通常是直接的父項或開啟器,但也可能不是 (例如當頁框瀏覽 iframe 中的 iframe 時)。
因為這樣會比較啟動器影格的「起點」,因此發起器影格可能位於從該來源的任何路徑。為清楚掌握這類情況,Chrome 要求任何內容指令碼若將 "match_origin_as_fallback"
設為 true
,也必須指定 *
的路徑。
如果同時指定 "match_origin_as_fallback"
和 "match_about_blank"
,則以 "match_origin_as_fallback"
為優先。
與嵌入頁面的通訊
雖然內容指令碼及其代管網頁的執行環境彼此獨立,但兩者共用網頁 DOM 的存取權。如果網頁想與內容指令碼或擴充功能通訊,必須透過共用 DOM 與擴充功能通訊。
可以使用 window.postMessage()
完成範例:
content-script.js
var port = chrome.runtime.connect();
window.addEventListener("message", (event) => {
// We only accept messages from ourselves
if (event.source !== window) {
return;
}
if (event.data.type && (event.data.type === "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
port.postMessage(event.data.text);
}
}, false);
example.js
document.getElementById("theButton").addEventListener("click", () => {
window.postMessage(
{type : "FROM_PAGE", text : "Hello from the webpage!"}, "*");
}, false);
非擴充功能的網頁 example.html 會將訊息訊息張貼到其本身。內容指令碼會攔截並檢查這則訊息,然後發布到擴充功能程序。這樣一來,頁面就會建立與擴充功能程序之間的通訊管道。反之亦然。
存取擴充功能檔案
如要從內容指令碼存取擴充功能檔案,您可以呼叫 chrome.runtime.getURL()
取得擴充功能素材資源的絕對網址,如以下範例 (content.js
) 所示:
content-script.js
let image = chrome.runtime.getURL("images/my_image.png")
如要在 CSS 檔案中使用字型或圖片,可以使用 @@extension_id
建構網址,如以下範例 (content.css
) 所示:
content.css
body {
background-image:url('chrome-extension://__MSG_@@extension_id__/background.png');
}
@font-face {
font-family: 'Stint Ultra Expanded';
font-style: normal;
font-weight: 400;
src: url('chrome-extension://__MSG_@@extension_id__/fonts/Stint Ultra Expanded.woff') format('woff');
}
所有資產都必須在 manifest.json
檔案中宣告為可供網路存取的資源:
manifest.json
{
...
"web_accessible_resources": [
{
"resources": [ "images/*.png" ],
"matches": [ "https://example.com/*" ]
},
{
"resources": [ "fonts/*.woff" ],
"matches": [ "https://example.com/*" ]
}
],
...
}
保障資料安全
雖然隔離的世界提供多一層保護,但使用內容指令碼可能會導致擴充功能和網頁中的安全漏洞。如果內容指令碼收到來自不同網站的內容 (例如呼叫 fetch()
),請務必先針對跨網站指令碼攻擊攻擊過濾內容,再插入指令碼。僅透過 HTTPS 進行通訊,以免發生"man-in-the-middle"攻擊。
請務必過濾惡意網頁。例如,下列在 Manifest V3 中都含有危險的模式:
content-script.js
const data = document.getElementById("json-data"); // WARNING! Might be evaluating an evil script! const parsed = eval("(" + data + ")");
content-script.js
const elmt_id = ... // WARNING! elmt_id might be '); ... evil script ... //'! window.setTimeout("animate(" + elmt_id + ")", 200);
建議您改用不會執行指令碼的安全 API:
content-script.js
const data = document.getElementById("json-data") // JSON.parse does not evaluate the attacker's scripts. const parsed = JSON.parse(data);
content-script.js
const elmt_id = ... // The closure form of setTimeout does not evaluate scripts. window.setTimeout(() => animate(elmt_id), 200);