2014年11月9日 星期日

Chrome Extension 開發經驗篇 16 - 如何在右鍵選單上顯示選取的文字?

Google 右鍵搜尋功能可以顯示選取的文字,如圖 1 所示。
01_google_search.png圖1. Google 右鍵搜尋
這是怎麼做到的呢? 來試著做一遍吧!

建立右鍵選單

首先,在右鍵選單中加上一個選項為『Hello, World!』。
Step 1. 在 manifest.json 設定檔中加入 context menu 功能。如下所示。
manifest.json
{
  ...
  "background": {
    "scripts": [
      "src/bg/event_page.js"
    ],
    "persistent": false
  },
  "permissions": [
    "contextMenus"
  ],
  ...
}
說明:這邊是使用事件頁面為範例,可參考官方提供的 『事件頁面版本』 及 『後台頁面版本』。
Step 2. 在事件頁面建立 context menu item。如下所示。
event_page.js
function onClickHandler(info, tab) {
  // to do something
}
chrome.contextMenus.onClicked.addListener(onClickHandler);

chrome.runtime.onInstalled.addListener(function (details) {
  chrome.contextMenus.create({
    type: 'normal',
    title: 'Hello, World!',
    id: 'myContextMenuItem',
    contexts: ['all']
  }, function () {
    console.log('contextMenus are create.');
  });
});
溫馨小提醒:如果是使用事件頁面,在建立右鍵選單時一定要給個 id。
Step 3. 建立完成後,右鍵選單就多出一個選項為 『Hello, World!』。如圖 2 所示。
02_hello_world.png圖2. 右鍵選單

顯示選取文字

建立好後,要在右鍵選單上顯示選取的文字,其實很簡單,只要在 title 裡加入 %s,就會顯示選取文字。如下所示。
event_page.js
...
chrome.runtime.onInstalled.addListener(function (details) {
  chrome.contextMenus.create({
    ...
    title: 'Hello, %s!',
    ...
  }, function () {
    // callback
  });
});
來看一下結果,如圖 3 所示。
03_selection_text.png圖3. 顯示選取文字

結語:

在右鍵選單顯示選取文字是不是很簡單啊!如果您有問題,歡迎在下方留言。謝謝!

沒有留言:

張貼留言