DIV CSS 佈局教程網

用 JavaScript 寫 Chrome 擴充功能:與瀏覽器互動及桌面通知
編輯:關於JavaScript     

一、與瀏覽器互動的常用 API

1. 書籤(chrome.bookmarks)

用來建立、整理與管理書籤,也可搭配 Override Pages 自訂書籤管理頁面。需在 manifest 中宣告權限:

{
  "name": "My extension",
  "permissions": [ "bookmarks" ]
}

書籤以樹狀結構組織,每個節點都是一個書籤或一組節點,對應一個 BookmarkTreeNode 物件。

// 建立書籤夾
chrome.bookmarks.create({
  'parentId': bookmarkBar.id,
  'title': 'Extension bookmarks'
}, function(newFolder) {
  console.log("added folder: " + newFolder.title);
});

// 建立指向文件的書籤
chrome.bookmarks.create({
  'parentId': extensionsFolderId,
  'title': 'Extensions doc',
  'url': 'https://code.google.com/chrome/extensions'
});

2. Cookies

{
  "name": "My extension",
  "permissions": [ "cookies", "*://*.google.com" ]
}

注意除了 cookies 權限,還必須用比對模式指定要存取的網域範圍。

3. 開發者工具

下列模組提供 devtools 的部分介面:devtools.inspectedWindow、devtools.network、devtools.panels。

{
  "name": "...",
  "version": "1.0",
  "minimum_chrome_version": "10.0",
  "devtools_page": "devtools.html"
}

4. 事件(Events)

Event 是一個物件,當你關注的事情發生時通知你。以下每當新分頁建立時就會收到通知:

chrome.tabs.onCreated.addListener(function(tab) {
  appendToLog('tabs.onCreated --'
    + ' window: ' + tab.windowId
    + ' tab: '    + tab.id
    + ' index: '  + tab.index
    + ' url: '    + tab.url);
});

任何 Event 物件都具備三個方法:

void addListener(function callback(...))
void removeListener(function callback(...))
bool hasListener(function callback(...))

5. 瀏覽歷史(chrome.history)

可新增、刪除、查詢瀏覽紀錄,需宣告 "history" 權限。

6. 擴充管理(chrome.management)

提供管理已安裝與執行中擴充/應用程式的能力,對要重寫內建新分頁頁的擴充特別有用,需宣告 "management" 權限。

7. 分頁(chrome.tabs)

用於建立、修改、重新排列瀏覽器分頁,需宣告 "tabs" 權限。

8. 視窗(chrome.windows)

用於建立、修改與重新排列瀏覽器視窗。

二、桌面通知的實作

1. 兩種建立方式

// 注意:沒有必要呼叫 webkitNotifications.checkPermission()
// 已宣告 notifications 權限的擴充永遠被允許建立通知

// 純文字通知
var notification = webkitNotifications.createNotification(
  '48.png',            // 圖示 URL,可用相對路徑
  '您好!',            // 標題
  '內容(Lorem ipsum...)' // 本文
);

// 或 HTML 通知
var notification = webkitNotifications.createHTMLNotification(
  'notification.html'  // HTML 的 URL
);

notification.show();

2. 通知與其他頁面的溝通

// 在通知中存取背景頁
chrome.extension.getBackgroundPage().doThing();

// 從背景頁反向操作所有通知視窗
chrome.extension.getViews({type:"notification"}).forEach(function(win) {
  win.doOtherThing();
});

3. 實例:每 10 秒彈出時間通知,共 10 次

manifest.json

{
  // 安裝對話框、擴充管理介面與商店中顯示的名稱
  "name": "系統通知",

  // 版本號以 1 到 4 組數字表示,以點分隔,各段須在 0 到 65535 之間
  "version": "1",

  // 描述不可含 HTML,長度上限 132 字元
  "description": "Shows off desktop notifications, which are \"toast\" windows that pop up on the desktop.",

  // 代表擴充的圖示
  "icons": {
    "16": "16.png",     // 網頁 favicon
    "48": "48.png",     // 管理頁面使用
    "128": "128.png"    // 商店安裝時使用
  },

  // 使用的權限
  "permissions": ["tabs", "notifications"],

  // Manifest V2 以 background 取代 background_page
  "background": {
    "scripts": ["background.js"]
  },

  "manifest_version": 2,

  // 對外公開、可被網頁存取的資源(相對於擴充根目錄)
  "web_accessible_resources": [ "48.png" ]
}

background.js

/** 顯示時間通知 */
function show() {
  var time = new Date().format('yyyy-MM-dd hh:mm:ss');
  var notification = window.webkitNotifications.createNotification(
    '48.png',          // 圖片需列入 web_accessible_resources
    '現在的時間是:',
    time
  );
  notification.show();
}

// 時間格式化
Date.prototype.format = function(format){
  var o = {
    "M+" : this.getMonth()+1,
    "d+" : this.getDate(),
    "h+" : this.getHours(),
    "m+" : this.getMinutes(),
    "s+" : this.getSeconds(),
    "q+" : Math.floor((this.getMonth()+3)/3),
    "S"  : this.getMilliseconds()
  };
  if(/(y+)/.test(format)) {
    format = format.replace(RegExp.$1,
      (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  }
  for(var k in o) {
    if(new RegExp("("+ k +")").test(format)) {
      format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
    }
  }
  return format;
};

// 先確認瀏覽器支援
if(window.webkitNotifications) {
  show();
  var interval = 0;
  var times = 10;
  var timer = setInterval(function() {
    interval++;
    if (10 <= interval) {
      show();
      interval = 0;
      times--;
      if(times < 0) clearInterval(timer);
    }
  }, 1000);
}

原始碼:https://github.com/arthinking/google-plugins/tree/master/example/notifications

實作上有兩點值得補充:一是 web_accessible_resources 必須把通知用的圖示列入白名單,否則通知會因為載不到圖示而顯示異常;二是 webkitNotifications 屬較早期的 API,新專案建議改用 Service Worker 搭配 Notification 介面,才能同時支援桌面與行動裝置,也更符合目前的標準方向。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved