注入内容脚本
学习如何将 JavaScript 和 CSS 注入特定网页,使扩展能够修改网页的外观与行为
注入内容脚本 是 CoddyKit 上的免费 Browser Extensions Development (Chrome & Edge) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Browser Extensions Development (Chrome & Edge) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Browser Extensions Development (Chrome & Edge) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What are Content Scripts?
Welcome to Content Scripts! These are JavaScript files that run in the context of web pages loaded in the browser.
Think of them as a bridge. They allow your extension to interact with the web page's content, just like a script running directly on that page.
- Read details from a page.
- Modify the page's appearance.
- Add or remove elements.
The Isolated World
Content scripts run in an 'isolated world'. This means they don't interfere with the page's own JavaScript environment.
Your script can access and modify the page's Document Object Model (DOM), but it can't directly access JavaScript variables or functions defined by the web page itself.
This isolation prevents conflicts and ensures your extension doesn't break the web page's functionality.
Static Injection via manifest.json
The simplest way to inject content scripts is by declaring them in your extension's manifest.json file.
These scripts will automatically load and run on web pages that match the patterns you specify. It's great for scripts that need to be active whenever a certain type of page loads.
Static JS Injection Example
Here's how you'd set up a content script in your manifest.json to inject a JavaScript file called content.js:
{ "manifest_version": 3,
"name": "My Page Modifier",
"version": "1.0",
"content_scripts": [
{
"matches": ["https://*.example.com/*"],
"js": ["content.js"]
}
]
}Static CSS Injection Example
You can also inject CSS files using the same content_scripts field in your manifest.json. This is perfect for custom styling!
The CSS will apply to matching pages, modifying their visual appearance.
{ "manifest_version": 3,
"name": "My Page Styler",
"version": "1.0",
"content_scripts": [
{
"matches": ["*://*.google.com/*"],
"css": ["content.css"]
}
]
}Programmatic Injection
Sometimes you need more control over when a script is injected. This is where programmatic injection comes in.
You can inject scripts dynamically based on user actions (like clicking a button in your popup) or specific conditions, rather than automatically on page load.
Using chrome.scripting.executeScript()
To inject scripts programmatically, you use the chrome.scripting.executeScript() API from your extension's background script or popup.
This method requires the scripting permission in your manifest.json.
- It targets a specific tab.
- You can inject a function or a file.
- Perfect for on-demand interactions.
Programmatic Code Demo
This example shows a background script injecting a simple function into the active tab when the extension icon is clicked.
The injected function changes the page's background color. Try running it!
// manifest.json snippet:
// {"permissions": ["activeTab", "scripting"]}
// background.js
chrome.action.onClicked.addListener(async (tab) => {
if (tab.url.startsWith("http")) {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
document.body.style.backgroundColor = 'lightblue';
console.log('Background changed!');
}
});
}
});Permissions & Best Practices
For programmatic injection, you'll typically need the activeTab and scripting permissions.
activeTab: Grants temporary host permissions to the currently active tab when the user invokes the extension.scripting: Allows using thechrome.scriptingAPI to inject code.
Always request the minimum necessary permissions for your extension's functionality.
Quick Check
Which of the following statements about content scripts is TRUE?
Recap: Injecting Content Scripts
You've learned how to inject content scripts into web pages!
- Content scripts let your extension interact with web pages.
- They run in an isolated world to prevent conflicts.
- You can inject them statically via
manifest.jsonfor automatic loading. - Or, inject them programmatically using
chrome.scripting.executeScript()for on-demand actions.
Next, we'll dive into how to modify the DOM of web pages using these powerful scripts!
常见问题解答
「注入内容脚本」课时是免费的吗?
是的 — 「注入内容脚本」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Browser Extensions Development (Chrome & Edge) 课程的其余内容,请升级到 CoddyKit PRO。 Browser Extensions Development (Chrome & Edge) 课程共包含 4 节课。
「注入内容脚本」这节课中我会学到什么?
学习如何将 JavaScript 和 CSS 注入特定网页,使扩展能够修改网页的外观与行为 你通过在浏览器中直接运行的动手代码来练习 Browser Extensions Development (Chrome & Edge),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Browser Extensions Development (Chrome & Edge) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Browser Extensions Development (Chrome & Edge) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「注入内容脚本」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Browser Extensions Development (Chrome & Edge) 课中编写并运行代码吗?
能。每节 Browser Extensions Development (Chrome & Edge) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。