[Chrome Extensions]從頭開始-淺解 Content Scripts

開發工具:EmEdit

開發環境:Google Chrome Canary

看了第一個官方提供的範例,及相關的延伸閱讀資後,相信對於 Chrome Extensions 已經介於一知半解的境界(@@),簡單的說,他就以 JavaScript 結合 Json 為主要開發手段的一種 HTML5 的網頁(或程式?)

下面來看一個官方所提供的例子就會更為了解一些以上的概念。

demo程式 set_page_color.7z (右鍵另開視窗下載)

這個範例主要是透過 Chrome Extensions 的 Content Scripts 來完成變更目前瀏覽頁面的背景顏色。

首先他準備了一個 icon.png 來準備做為 Extensions 的 icon,再來搭配 manifest.json 來完成整個 Extensions 的配置。

manifest.json

{

  "name": "A browser action with a popup that changes the page color",

  "description": "Change the current page color",

  "version": "1.0",

  "permissions": [

    "tabs", "http://*/*", "https://*/*"

  ],

  "browser_action": {

      "default_title": "Set this page's color.",

      "default_icon": "icon.png",

      "default_popup": "popup.html"

  },

  "manifest_version": 2

}

一樣是採用 chrome.browserAction 的方式,而其 script 的設定非採用 “scripts”: [“popup.js”] 的 方式,而在採用設定在 popup.html 當中的方式 <script src="popup.js"></script>,當然,兩種方式都可以達成相同的效果,就看使用的情境而來決定。

另外在 permissions 一樣有使用 Match Patterns 當作樣板,比較特別的地方有個 tabs ,下面放上官方說明

Gives your extension access to privileged fields of the Tab objects used by several APIs including chrome.tabs and chrome.windows. In many circumstances your extension will not need to declare the "tabs" permission to make use of these APIs.

簡單說明,就是讓我們的 Tab object 有存取 chrome.tabs / chrome.windows 的權限

我們的 Content Scripts 要能夠存取個頁面上的原件時,都必須加上相關的權限,在 popup.js 就有使用到:

 function click(e) {

  chrome.tabs.executeScript(null,

      {code:"document.body.style.backgroundColor='" + e.target.id + "'"});

  window.close();

}

document.addEventListener('DOMContentLoaded', function () {

  var divs = document.querySelectorAll('div');

  for (var i = 0; i < divs.length; i++) {

    divs[i].addEventListener('click', click);

  }

});

若你對 HTML 的 DOM 很熟悉,那看到上面的語法一定不陌生,為每個 Div 加入一個 Listener(click) ,注意的是最後在 click(e) 中有對 chrome.tabs API 做存取的動作,所以我們在 manifest.json 需要加入存取權限。

executeScript

chrome.tabs.executeScript(integer tabId, tabs.InjectDetails details, function callback)

Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc.

可以自己 Run 一下 Extensions 的效果!!!

如果要執行的是 CSS 則使用 insertCSS

insertCSS

chrome.tabs.insertCSS(integer tabId, tabs.InjectDetails details, function callback)

Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc.