我有一個瀏覽器擴展,它執行以下操作:
- 在
document_start
處執行內容腳本。
- 此內容腳本在我的擴展中插入一個帶有 JavaScript 文件的
src
屬性的<script>
元素。
- 這個 JavaScript 文件掛鈎了一些瀏覽器功能。
所有這三件事都需要在加載的頁面上運行任何腳本之前發生。 為此,我在manifest.json
創建了以下內容:
"content_scripts": [
{
"matches": [
"https://example.com/*",
],
"run_at": "document_start",
"js": ["js/inject.js"]
}
]
然后對於inject.js
:
console.log('Inject');
const scriptEl = document.createElement('script');
scriptEl.src = chrome.runtime.getURL('js/hooks.js');
(document.head || document.documentElement).appendChild(scriptEl);
在hooks.js
,現在,只是一些調試:
console.log('Hooks');
最后,在我的測試 HTML 頁面上,我還有一些腳本:
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', async (e) => {
console.log('DOMContentLoaded');
});
</script>
</head>
<body>
<h1>Test Page</h1>
</body>
</html>
我期待在控制台上按以下順序看到以下內容:
Inject
Hooks
DOMContentLoaded
相反,我看到的是:
Inject
DOMContentLoaded
Hooks
如果我使用瀏覽器的開發人員工具檢查 DOM,我會看到<script src=".../js/hooks.js"></script>
緊接在<head>
之前插入。 這是注入方法所預期的。
有沒有辦法讓這個腳本在所有其他腳本之前執行?