如何开发一个 chrome 扩展工具

2020-01-20  本文已影响0人  风之化身呀

组成

步骤

新建一个文件夹 chrome-extention-demo

{
    "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 加载该文件夹

右上角也会出现该扩展:


后台脚本相当于一个总控制器,可以协调各组成部分之间的通信,如数据共享等。
新建一个 background.js,并注册和申请 storage 权限(chrome很多 api 的使用都需要申请权限)

  {
    "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中重新加载该扩展:


点击背景页后:


// 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
}

此时重新加载该插件,右上角图标会是灰色的,表示插件尚未初始化完成



修改 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 ,新加了一个匹配规则,当页面 host 是 developer.chrome.com 时就展示 page_action 注册的页面:


目前这个弹出页面是静态的,没有任何交互操作,所以再新建一个 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,固需要申请:

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

现在就实现了点击 button 后,整个页面背景都变成 green 色了:


 <!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>

新建一个 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);

注册配置页面:

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

可通过以下方式访问到:




效果如下:



点击选中某个颜色,该颜色就会传给右上角那个button,再点击右上角button就可以改变背景颜色咯。

参考

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

上一篇 下一篇

猜你喜欢

热点阅读