Example Extension Folder Structure
-<root_folder>
|- manifest.json
|- popup.html
|- background.js
|- content.js
Tips
- 由于 Chrome 的安全限制,Popup 页等 html 里不能使用 inline js 和 inline DOM level 0 event 定义(即 html内联的
onclick="..."
风格 event handler)。所有 js 代码必须写在单独的外部文件里然后通过<script src="..."></script>
引用。 - 右击 Chrome omnibar 里的扩展图标选择“Inspect Popup”可以打开 Chrome Developer Tool 调试 Popup 页面
Manifest
manifest.json
其中引用的 popup.html, background.js 等均为相对扩展根目录的相对路径。
{
"name": "Demo Extension",
"description": "demo extension",
"version": "1.0.0",
"author": "Foo Bar",
"manifest_version": 2,
"permissions": ["tabs"],
"browser_action": {
"default_title": "Demo extension",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [
{
"js": [
"content.js"
],
"matches": [
"http://*/*",
"https://*/*"
],
"run_at": "document_start",
"all_frames": false
}
]
}
Popup <-> Background interaction
Popup 与 Background 位于同一进程,可以直接通信。
in Popup:
chrome.extension.getBackgroundPage().variable = 42;
in Background:
var popups = chrome.extension.getViews({type: "popup"});
if (0 < popups.length)
popups[0].variable = 42;
Content Script -> Background
in Content Script:
chrome.runtime.sendMessage({text: "hey"}, function(response) {
console.log("Response: ", response);
});
in Background:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
// sender.tab.id
console.log("Received %o from %o, frame", msg, sender.tab, sender.frameId);
sendResponse("Gotcha!");
});
另,很多 API,如 chrome.storage,支持在 Content Scripts 里直接调用。
Background / Popup -> Content Script
Background:
chrome.tabs.sendMessage(tabId, message, (response) => {
console.log(response);
});
Content Script:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message);
sendResponse({});
});
这种方法需要知道目标 tab 的 id, 参考下面.
Track current active tab in Background
Background:
var data = {
tabId: '',
};
chrome.tabs.onActivated.addListener(({tabId, windowId}) => {
data.tabId = tabId;
chrome.tabs.get(tabId, ({status, title, url}) => {
// get tab details
});
});
Track tab content change
监测 Tab 页内容变化(如 url 变化即代表点击了一个链接等)
// 回调函数的参数类型为object,其各属性均为 optional, 为发生变动项的新值
// status: loading|complete
chrome.tabs.onUpdated.addListener(async (tabId, {status, title, url}) => {
if( url ) {
}
});