Chrome Extension Development

Chrome Extension Development

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 ) {

  }
});

Last update: 2018-04-04 01:20:30 UTC
``` 引用。\n* 右击 Chrome omnibar 里的扩展图标选择“Inspect Popup”可以打开 Chrome Developer Tool 调试 Popup 页面\n\n\n# Manifest\n\nmanifest.json\n\n其中引用的 popup.html, background.js 等均为相对扩展根目录的相对路径。\n\n```json\n{\n \"name\": \"Demo Extension\",\n \"description\": \"demo extension\",\n \"version\": \"1.0.0\",\n \"author\": \"Foo Bar\",\n \"manifest_version\": 2,\n \"permissions\": [\"tabs\"],\n \"browser_action\": {\n \"default_title\": \"Demo extension\",\n \"default_popup\": \"popup.html\"\n },\n \"background\": {\n \"scripts\": [\"background.js\"],\n \"persistent\": true\n },\n \"content_scripts\": [\n {\n \"js\": [\n \"content.js\"\n ],\n \"matches\": [\n \"http://*/*\",\n \"https://*/*\"\n ],\n \"run_at\": \"document_start\",\n \"all_frames\": false\n }\n ]\n}\n```\n\n# Popup <-> Background interaction\n\nPopup 与 Background 位于同一进程,可以直接通信。\n\nin Popup:\n\n```js\nchrome.extension.getBackgroundPage().variable = 42;\n```\n\nin Background:\n```js\nvar popups = chrome.extension.getViews({type: \"popup\"});\nif (0 < popups.length)\n popups[0].variable = 42;\n```\n\n# Content Script -> Background\n\nin Content Script:\n```js\nchrome.runtime.sendMessage({text: \"hey\"}, function(response) {\n console.log(\"Response: \", response);\n});\n```\n\nin Background:\n```js\nchrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {\n // sender.tab.id\n console.log(\"Received %o from %o, frame\", msg, sender.tab, sender.frameId);\n sendResponse(\"Gotcha!\");\n});\n```\n\n另,很多 API,如 chrome.storage,支持在 Content Scripts 里直接调用。\n\n# Background / Popup -> Content Script\n\nBackground:\n```js\nchrome.tabs.sendMessage(tabId, message, (response) => {\n console.log(response);\n});\n```\n\nContent Script:\n```js\nchrome.runtime.onMessage.addListener((message, sender, sendResponse) => {\n console.log(message);\n sendResponse({});\n});\n```\n\n这种方法需要知道目标 tab 的 id, 参考下面.\n\n# Track current active tab in Background\n\n\nBackground:\n```js\nvar data = {\n tabId: '',\n};\n\nchrome.tabs.onActivated.addListener(({tabId, windowId}) => {\n data.tabId = tabId;\n chrome.tabs.get(tabId, ({status, title, url}) => {\n // get tab details\n });\n});\n```\n\n# Track tab content change\n\n监测 Tab 页内容变化(如 url 变化即代表点击了一个链接等)\n\n```js\n// 回调函数的参数类型为object,其各属性均为 optional, 为发生变动项的新值\n// status: loading|complete\nchrome.tabs.onUpdated.addListener(async (tabId, {status, title, url}) => {\n if( url ) {\n\n }\n});\n```\n\n","note":null,"ctime":"2018-02-08T02:32:58.195Z","mtime":"2018-04-04T01:20:30.792Z","meta":[{"id":519,"title":"Chrome Extension Development","name":"tag","value":"chrome","note":null,"ctime":"2018-02-08T02:34:24.944Z","mtime":"2018-02-08T02:34:24.944Z"}]},"status":200,"parentMetas":[]},"serverParams":{"csrf":"E9WW5tul-LFEQZMfe5danIro4DgAnW0VMg2U","old":false}}; //-->