如何開發(fā)一個(gè) chrome 擴(kuò)展工具

組成

  • 后臺(tái)腳本(background scripts)
  • 內(nèi)容腳本(content scripts)
  • 配置頁面(options page)
  • UI 元素(UI elements)

步驟

新建一個(gè)文件夾 chrome-extention-demo

  • 新建 manifest.json 和 images 文件夾
{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "icons": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    },
    "manifest_version": 1
  }

打開chrome://extensions 加載該文件夾

右上角也會(huì)出現(xiàn)該擴(kuò)展:


  • 使用后臺(tái)腳本

后臺(tái)腳本相當(dāng)于一個(gè)總控制器,可以協(xié)調(diào)各組成部分之間的通信,如數(shù)據(jù)共享等。
新建一個(gè) background.js,并注冊(cè)和申請(qǐng) storage 權(quán)限(chrome很多 api 的使用都需要申請(qǐng)權(quán)限)

  {
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "permissions": ["storage"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "manifest_version": 2
  }

background.js

'use strict';

chrome.runtime.onInstalled.addListener(function () {
  chrome.storage.sync.set({
    color: '#3aa757'
  }, function () {
    console.log("The color is green.");
  });
});

在chrome中重新加載該擴(kuò)展:


點(diǎn)擊背景頁后:


  • 用戶界面
    就是用來定制右上角的 icon 點(diǎn)擊之后的頁面,這里采用點(diǎn)擊后彈出一個(gè)頁面的方式。新增 page_action 字段
// manifest.json
{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "icons": {
    "16": "images/get_started16.png",
    "32": "images/get_started32.png",
    "48": "images/get_started48.png",
    "128": "images/get_started128.png"
  },
  "permissions": ["declarativeContent", "storage"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "page_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    }
  },
  "manifest_version": 2
}

此時(shí)重新加載該插件,右上角圖標(biāo)會(huì)是灰色的,表示插件尚未初始化完成



修改 background.js

  chrome.runtime.onInstalled.addListener(function() {
    chrome.storage.sync.set({color: '#3aa757'}, function() {
      console.log('The color is green.');
    });
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
      chrome.declarativeContent.onPageChanged.addRules([{
        conditions: [new chrome.declarativeContent.PageStateMatcher({
          pageUrl: {hostEquals: 'developer.chrome.com'},
        })
        ],
        actions: [new chrome.declarativeContent.ShowPageAction()]
      }]);
    });
  });

這里使用了 declarativeContent API ,新加了一個(gè)匹配規(guī)則,當(dāng)頁面 host 是 developer.chrome.com 時(shí)就展示 page_action 注冊(cè)的頁面:


目前這個(gè)彈出頁面是靜態(tài)的,沒有任何交互操作,所以再新建一個(gè) popup.js 做交互:

  let changeColor = document.getElementById('changeColor');

  chrome.storage.sync.get('color', function(data) {
    changeColor.style.backgroundColor = data.color;
    changeColor.setAttribute('value', data.color);
  });

  changeColor.onclick = function(element) {
    let color = element.target.value;
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.executeScript(
          tabs[0].id,
          {code: 'document.body.style.backgroundColor = "' + color + '";'});
    });
  };

由于使用了 activeTabs API,固需要申請(qǐng):

"permissions": ["activeTab", "declarativeContent", "storage"],

現(xiàn)在就實(shí)現(xiàn)了點(diǎn)擊 button 后,整個(gè)頁面背景都變成 green 色了:


  • 配置頁面
    上面的實(shí)現(xiàn)只能設(shè)置一種顏色,可以提供一個(gè)配置頁,來讓用戶選擇用哪種背景。
    新建一個(gè) option.html:
 <!DOCTYPE html>
  <html>
    <head>
      <style>
        button {
          height: 30px;
          width: 30px;
          outline: none;
          margin: 10px;
        }
      </style>
    </head>
    <body>
      <div id="buttonDiv">
      </div>
      <div>
        <p>Choose a different background color!</p>
      </div>
    </body>
    <script src="options.js"></script>
  </html>

新建一個(gè) option.js :

  let page = document.getElementById('buttonDiv');
  const kButtonColors = ['#3aa757', '#e8453c', '#f9bb2d', '#4688f1'];
  function constructOptions(kButtonColors) {
    for (let item of kButtonColors) {
      let button = document.createElement('button');
      button.style.backgroundColor = item;
      button.addEventListener('click', function() {
        chrome.storage.sync.set({color: item}, function() {
          console.log('color is ' + item);
        })
      });
      page.appendChild(button);
    }
  }
  constructOptions(kButtonColors);

注冊(cè)配置頁面:

  {
    "name": "Getting Started Example",
    ...
    "options_page": "options.html",
    ...
    "manifest_version": 2
  }

可通過以下方式訪問到:




效果如下:



點(diǎn)擊選中某個(gè)顏色,該顏色就會(huì)傳給右上角那個(gè)button,再點(diǎn)擊右上角button就可以改變背景顏色咯。

參考

https://developer.chrome.com/extensions/getstarted

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容