Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

context-menu

翻譯不完整。請協助 翻譯此英文文件

Stable

加入選單項目、子選單、選單分隔線到頁面右鍵選單。

用法

Instead of manually adding items when particular contexts occur and then removing them when those contexts go away, you bind items to contexts, and the adding and removing is automatically handled for you. Items are bound to contexts in much the same way that event listeners are bound to events. When the user invokes the context menu, all of the items bound to the current context are automatically added to the menu. If no items are bound, none are added. Likewise, any items that were previously in the menu but are not bound to the current context are automatically removed from the menu. You never need to manually remove your items from the menu unless you want them to never appear again.

For example, if your add-on needs to add a context menu item whenever the user visits a certain page, don't create the item when that page loads, and don't remove it when the page unloads. Rather, create your item only once and supply a context that matches the target URL.

Context menu items are displayed in the order created or in the case of sub menus the order added to the sub menu. Menu items for each add-on will be grouped together automatically. If the total number of menu items in the main context menu from all add-ons exceeds a certain number (normally 10 but configurable with the extensions.addon-sdk.context-menu.overflowThreshold preference) all of the menu items will instead appear in an overflow menu to avoid making the context menu too large.

Specifying Contexts

As its name implies, the context menu should be reserved for the occurrence of specific contexts. Contexts can be related to page content or the page itself, but they should never be external to the page.

For example, a good use of the menu would be to show an "Edit Image" item when the user right-clicks an image in the page. A bad use would be to show a submenu that listed all the user's tabs, since tabs aren't related to the page or the node the user clicked to open the menu.

The Page Context

First of all, you may not need to specify a context at all. When a top-level item does not specify a context, the page context applies. An item that is in a submenu is visible unless you specify a context.

The page context occurs when the user invokes the context menu on a non-interactive portion of the page. Try right-clicking a blank spot in this page, or on text. Make sure that no text is selected. The menu that appears should contain the items "Back", "Forward", "Reload", "Stop", and so on. This is the page context.

The page context is appropriate when your item acts on the page as a whole. It does not occur when the user invokes the context menu on a link, image, or other non-text node, or while a selection exists.

宣告式場景條件(Declarative Contexts)

當你藉由設定 context 屬性(該屬性為: 傳給 constructor 的選項物件之屬性)來新增選單項目時,你可以指定一些簡單的宣告式場景條件, 如下:

var cm = require("sdk/context-menu");
cm.Item({
  label: "My Menu Item",
  context: cm.URLContext("*.mozilla.org")
});
Constructor 選單項目出現的條件
PageContext() 當場景為網頁時.
SelectionContext() 當使用者在網頁上選取項目時.
SelectorContext(selector) 當選單在符合下述條件之一的節點上顯示: selector匹配, CSS 選擇器, 或 其祖先節點匹配選擇器. selector可以有多個(以逗點分隔), 例如, "a[href], img".
URLContext(matchPattern) 特定網址的網頁. matchPattern is a match pattern string or an array of match pattern strings. 當 matchPattern 是陣列, 網址符合任何陣列元素之一時. These are the same match pattern strings that you use with the page-mod include property. Read more about patterns.
PredicateContext(predicateFunction) 當選單被觸發時,predicateFunction 函數被呼叫,若函數傳回值為真值,則選單項目顯示。這函數傳入一物件,物件有著描述選單觸發場景條件的屬性.
array An array of any of the other types. This context occurs when all contexts in the array occur.

選單項目也有 context 屬性,可以用在新增或移除宣告式場景條件,當建構後. 例如:

var context = require("sdk/context-menu").SelectorContext("img");
myMenuItem.context.add(context);
myMenuItem.context.remove(context);

當選單項目被指定了多個場景條件, 選單項目顯示於所有場景條件皆成立時.

In Content Scripts

宣告式場景條件很容易使用,但功能不強. 舉例來說, 你希望選單項目出現的條件為:「有著至少一張圖片的頁面」, 但宣告式場景條件並不能達成這一點.

當你需要對選單項目的出現時機有著更多的控制, 你可以使用 content scripts. 如同 SDK 的其他 APIs 一樣, context-menu API 使用 content scripts 以讓你的附加元件與瀏覽器中的頁面互動. 在最上層選單的每一個選單項目可以使用 content script.

每當選單即將顯示時,一個特殊事件,其名為 "context" ,觸發於你的 content scripts. 如果你為這個事件註冊了偵聽(listener)函數,當函數傳回真值時, 與偵聽函數關聯的選單項目會被顯示於選單中.

下例中, 當選單觸發於「有著至少一張圖片的頁面」時,顯示選單項目.

require("sdk/context-menu").Item({
  label: "This Page Has Images",
  contentScript: 'self.on("context", function (node) {' +
                 '  return !!document.querySelector("img");' +
                 '});'
});

需要注意的是偵聽函數有一個參數叫 node. 這個 node 指的是使用者在頁面上按右鍵來觸發選單的頁面觸發節點. 你可以使用它來決定是否要顯示選單項目.

你可以在 content script 中,同時指定宣告式場景條件和 context 偵聽函數. 在這種情況下, 先評估宣告式場景條件, 然後你的選單項目顯示條件為:所有宣告式場景條件成立,並且你的 context 偵聽函數傳回真值.

如果任一宣告式場景條件未成立, 那麼你的 context 偵聽函數不會被呼叫. 下面的例子利用了這點. 確保了偵聽函數只在 image node 上觸發選單時,才會被呼叫:

var cm = require("sdk/context-menu");
cm.Item({
  label: "A Mozilla Image",
  context: cm.SelectorContext("img"),
  contentScript: 'self.on("context", function (node) {' +
                 '  return /mozilla/.test(node.src);' +
                 '});'
});

However, if you do combine SelectorContext and the "context" event, be aware that the node argument passed to the "context" event will not always match the type specified in SelectorContext.

SelectorContext will match if the menu is invoked on the node specified or any descendant of that node, but the "context" event handler is passed the actual node on which the menu was invoked. 上個例子有作用,是因為 <IMG> 元素內不能包含其他元素, 但底下的例子裡, node.nodeName 不能保證是 "P" - 例如說, 當使用者在一個段落(<P>)的連結(<A>)上點右鍵時,它不會是 "P" :

var cm = require("sdk/context-menu");
cm.Item({
  label: "A Paragraph",
  context: cm.SelectorContext("p"),
  contentScript: 'self.on("context", function (node) {' +
                 '  console.log(node.nodeName);' +
                 '  return true;' +
                 '});'
});

The content script is executed for every page that a context menu is shown for. It will be executed the first time it is needed (i.e. 當右鍵選單第一次顯示,並且選單項目的所有宣告式場景條件皆成立時) ,接著處於作用中,直到你銷毀你的選單項目或者關閉頁面.

處理選單項目上的點擊

content script 除了上述所說的功能(用來偵聽 "context" 事件)以外,你可以使用 content script 來處理選單項目上的點擊. 當使用者點擊選單項目時,一個名為 "click" 的事件在選單項目的 content script 內被觸發.

因此, 欲處理選單項目上的點擊, 可以藉由偵聽選單項目 content script 內的 "click" 事件, 如下:

require("sdk/context-menu").Item({
  label: "My Item",
  contentScript: 'self.on("click", function (node, data) {' +
                 '  console.log("Item clicked!");' +
                 '});'
});

注意:偵聽函數有兩參數 nodedata.

"node" 參數

node 是使用者右鍵點擊所觸發選單的節點.

  • 如果你未使用 SelectorContext 來決定是否顯示選單項目, 那麼這實際點擊的節點.
  • 如果你使用了 SelectorContext, 那麼這是符合你的選擇器的那個節點.

例如, 假設你的附加元件看起來像這樣:

var script = "self.on('click', function (node, data) {" +
             "  console.log('clicked: ' + node.nodeName);" +
             "});";

var cm = require("sdk/context-menu");

cm.Item({
  label: "body context",
  context: cm.SelectorContext("body"),
  contentScript: script
});

這個附加元件建立了一個右鍵選單項目,該項目使用 SelectorContext 來顯示項目,顯示時機為:右鍵選單觸發於 <BODY> 元素的任何後代元素之上時. 點擊時, 項目記錄了 nodeName 屬性(觸發選單的節點名稱)傳給點擊事件處理器.

如果你執行這個附加元件,你將看到它總是記錄 "BODY", 即使你點擊的是頁面上的段落元素<P>:

info: contextmenu-example: clicked: BODY

與上面對比, 底下的附加元件使用了 PageContext:

var script = "self.on('click', function (node, data) {" +
             "  console.log('clicked: ' + node.nodeName);" +
             "});";

var cm = require("sdk/context-menu");

cm.Item({
  label: "body context",
  context: cm.PageContext(),
  contentScript: script
});

它將記錄實際點擊的節點名稱:

info: contextmenu-example: clicked: P

"data" 參數

data 是使用者所點擊選單項目的 data屬性. 注意: 當你有一個多層的選單(項目)時,點擊事件會被傳給被點擊的項目的所有祖先(項目),所以一定要驗證 data 值傳給你所期待的項目. 你可以使用 "data" 參數來簡化點擊事件處理 by providing just a single click listener on a Menu that reacts to clicks for any child items.:

var cm = require("sdk/context-menu");
cm.Menu({
  label: "My Menu",
  contentScript: 'self.on("click", function (node, data) {' +
                 '  console.log("You clicked " + data);' +
                 '});',
  items: [
    cm.Item({ label: "Item 1", data: "item1" }),
    cm.Item({ label: "Item 2", data: "item2" }),
    cm.Item({ label: "Item 3", data: "item3" })
  ]
});

和附加元件通訊

時常,你需要收集一些訊息,在點擊偵聽函數內和執行一個無關於頁面動作. 為了與關聯於 content script 的選單項目通訊, content script 可以呼叫附屬於全域 self 物件的 postMessage 函數, 傳給它一些 JSON-able 資料. 選單項目的 "message" 事件偵聽函數將被呼叫(前述的 JSON-able 資料作為參數傳入).

var cm = require("sdk/context-menu");
cm.Item({
  label: "Edit Image",
  context: cm.SelectorContext("img"),
  contentScript: 'self.on("click", function (node, data) {' +
                 '  self.postMessage(node.src);' +
                 '});',
  onMessage: function (imgSrc) {
    openImageEditor(imgSrc);
  }
});

更新選單項目的文字標籤

Each menu item must be created with a label, but you can change its label later using a couple of methods.

最簡單的方法是設定選單項目的 label 屬性. 下面的例子更新選單項目的文字標籤為它被點擊的次數:

var numClicks = 0;
var myItem = require("sdk/context-menu").Item({
  label: "Click Me: " + numClicks,
  contentScript: 'self.on("click", self.postMessage);',
  onMessage: function () {
    numClicks++;
    this.label = "Click Me: " + numClicks;
    // Setting myItem.label is equivalent.
  }
});

Sometimes you might want to update the label based on the context. For instance, if your item performs a search with the user's selected text, it would be nice to display the text in the item to provide feedback to the user. 在這些情況下,你可以使用第二種方法 . 回想一下,你的 content scripts 可以偵聽 "context" 事件,如果你的偵聽函數傳回真值, 與 content scripts 關聯的選單項目會顯示在選單中. 除了傳回真值, 你的 "context" 偵聽函數也可以傳回字串. 當 "context" 偵聽函數傳回字串, 字串成為選單項目的新文字標籤.

This item implements the aforementioned search example:

var cm = require("sdk/context-menu");
cm.Item({
  label: "Search Google",
  context: cm.SelectionContext(),
  contentScript: 'self.on("context", function () {' +
                 '  var text = window.getSelection().toString();' +
                 '  if (text.length > 20)' +             // 若太長
                 '    text = text.substr(0, 20) + "...";' + // 則截短
                 '  return "Search Google for " + text;' +  // 後綴到固定字串上傳回
                 '});'
});

"context" 偵聽函數取得使用者所選取的文字, 如果字串太長則截短它, 並後綴到固定字串上傳回. 當選單項目顯示, 它的文字標籤將是 "Search Google for text", 此處的 text 是被截短的 使用者所選取的文字.

隱私視窗

If your add-on has not opted into private browsing, then any menus or menu items that you add will not appear in context menus belonging to private browser windows.

To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module.

更多例子

For conciseness, these examples create their content scripts as strings and use the contentScript property. In your own add-on, you will probably want to create your content scripts in separate files and pass their URLs using the contentScriptFile property. See Working with Content Scripts for more information.

Unless your content script is extremely simple and consists only of a static string, don't use contentScript: if you do, you may have problems getting your add-on approved on AMO.

Instead, keep the script in a separate file and load it using contentScriptFile. This makes your code easier to maintain, secure, debug and review.

Show an "Edit Page Source" item when the user right-clicks a non-interactive part of the page:

require("sdk/context-menu").Item({
  label: "Edit Page Source",
  contentScript: 'self.on("click", function (node, data) {' +
                 '  self.postMessage(document.URL);' +
                 '});',
  onMessage: function (pageURL) {
    editSource(pageURL);
  }
});

Show an "Edit Image" item when the menu is invoked on an image:

var cm = require("sdk/context-menu");
cm.Item({
  label: "Edit Image",
  context: cm.SelectorContext("img"),
  contentScript: 'self.on("click", function (node, data) {' +
                 '  self.postMessage(node.src);' +
                 '});',
  onMessage: function (imgSrc) {
    openImageEditor(imgSrc);
  }
});

Show an "Edit Mozilla Image" item when the menu is invoked on an image in a mozilla.org or mozilla.com page:

var cm = require("sdk/context-menu");
cm.Item({
  label: "Edit Mozilla Image",
  context: [
    cm.URLContext(["*.mozilla.org", "*.mozilla.com"]),
    cm.SelectorContext("img")
  ],
  contentScript: 'self.on("click", function (node, data) {' +
                 '  self.postMessage(node.src);' +
                 '});',
  onMessage: function (imgSrc) {
    openImageEditor(imgSrc);
  }
});

Show an "Edit Page Images" item when the page contains at least one image:

var cm = require("sdk/context-menu");
cm.Item({
  label: "Edit Page Images",
  // This ensures the item only appears during the page context.
  context: cm.PageContext(),
  contentScript: 'self.on("context", function (node) {' +
                 '  var pageHasImgs = !!document.querySelector("img");' +
                 '  return pageHasImgs;' +
                 '});' +
                 'self.on("click", function (node, data) {' +
                 '  var imgs = document.querySelectorAll("img");' +
                 '  var imgSrcs = [];' +
                 '  for (var i = 0 ; i < imgs.length; i++)' +
                 '    imgSrcs.push(imgs[i].src);' +
                 '  self.postMessage(imgSrcs);' +
                 '});',
  onMessage: function (imgSrcs) {
    openImageEditor(imgSrcs);
  }
});

Show a "Search With" menu when the user right-clicks an anchor that searches Google or Wikipedia with the text contained in the anchor:

var cm = require("sdk/context-menu");
var googleItem = cm.Item({
  label: "Google",
  data: "https://www.google.com/search?q="
});
var wikipediaItem = cm.Item({
  label: "Wikipedia",
  data: "https://en.wikipedia.org/wiki/Special:Search?search="
});
var searchMenu = cm.Menu({
  label: "Search With",
  context: cm.SelectorContext("a[href]"),
  contentScript: 'self.on("click", function (node, data) {' +
                 '  var searchURL = data + node.textContent;' +
                 '  window.location.href = searchURL;' +
                 '});',
  items: [googleItem, wikipediaItem]
});

Globals

Constructors

Item(options)

建立一個有文字標籤的選單項目,當點擊它時,可以執行一些動作.

參數

options : 物件
options 物件的必要屬性:

名稱 型別  
label 字串

選單項目的文字標籤. It must either be a string or an object that implements toString().

options 物件的可選屬性:

名稱 型別  
image 字串

選單項目的圖示, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI.

data 字串

An optional arbitrary value to associate with the item. It must be either a string or an object that implements toString(). It will be passed to click listeners.

accessKey 只有單一字元的字串

New in Firefox 35.

選單項目的快捷鍵. Pressing this key selects the item when the context menu is open.

context value

If the item is contained in the top-level context menu, this declaratively specifies the context under which the item will appear; see Specifying Contexts above.

contentScript 字串, 陣列

If the item is contained in the top-level context menu, this is the content script or an array of content scripts that the item can use to interact with the page.

contentScriptFile 字串, 陣列

If the item is contained in the top-level context menu, this is the local file URL of the content script or an array of such URLs that the item can use to interact with the page.

onMessage 函數

If the item is contained in the top-level context menu, this function will be called when the content script calls self.postMessage. It will be passed the data that was passed to postMessage.

建立一個有文字標籤的選單項目,用以展開子選單.

參數

options : 物件
options 物件的必要屬性:

名稱 型別  
label 字串

選單項目的文字標籤. It must either be a string or an object that implements toString().

items 陣列

選單項目構成的陣列,這些選單項目會被子選單所包含. 陣列中的元素須為 Item, Menu, 或 Separator.

options 物件的可選屬性:

名稱 型別  
image 字串

The menu's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI.

context value

If the menu is contained in the top-level context menu, this declaratively specifies the context under which the menu will appear; see Specifying Contexts above.

contentScript 字串, 陣列

If the menu is contained in the top-level context menu, this is the content script or an array of content scripts that the menu can use to interact with the page.

contentScriptFile 字串, 陣列

If the menu is contained in the top-level context menu, this is the local file URL of the content script or an array of such URLs that the menu can use to interact with the page.

onMessage 函數

If the menu is contained in the top-level context menu, this function will be called when the content script calls self.postMessage. It will be passed the data that was passed to postMessage.

Separator()

Creates a menu separator.

PageContext()

Creates a page context. See Specifying Contexts above.

SelectionContext()

Creates a context that occurs when a page contains a selection. See Specifying Contexts above.

SelectorContext(selector)

Creates a context that matches a given CSS selector. See Specifying Contexts above.

Parameters

selector : string
A CSS selector.

URLContext(matchPattern)

Creates a context that matches pages with particular URLs. See Specifying Contexts above.

Parameters

matchPattern : string,array
A match pattern string, regexp or an array of match pattern strings or regexps.

PredicateContext(predicateFunction)

New in Firefox 29

Creates a context that occurs when predicateFunction returns a true value. See Specifying Contexts above.

Parameters

predicateFunction : function(context)
A function which will be called with an object argument that provide information about the invocation context. context object properties:

Property Description
documentType The MIME type of the document the menu was invoked in. E.g. text/html for HTML pages, application/xhtml+xml for XHTML, or image/jpeg if viewing an image directly.
documentURL The URL of the document the menu was invoked in.
targetName The name of the DOM element that the menu was invoked on, in lower-case.
targetID The id attribute of the element that the menu was invoked on, or null if not set.
isEditable true if the menu was invoked in an editable element, and that element isn't disabled or read-only.  This includes non-input elements with the contenteditable attribute set to true.
selectionText The current selection as a text string, or null. If the menu was invoked in an input text box or area, this is the selection of that element, otherwise the selection in the contents of the window.
srcURL The src URL of the element that the menu was invoked on, or null if it doesn't have one.
linkURL The href URL of the element that the menu was invoked on, or null if it doesn't have one.
value The current contents of a input text box or area if the menu was invoked in one, null otherwise.

Item

A labeled menu item that can perform an action when clicked.

Methods

destroy()

Permanently removes the item from its parent menu and frees its resources. The item must not be used afterward. If you need to remove the item from its parent menu but use it afterward, call removeItem() on the parent menu instead.

Properties

label

The menu item's label. You can set this after creating the item to update its label later.

image

The item's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI. You can set this after creating the item to update its image later. To remove the item's image, set it to null.

data

An optional arbitrary value to associate with the item. It must be either a string or an object that implements toString(). It will be passed to click listeners. You can set this after creating the item to update its data later.

context

A list of declarative contexts for which the menu item will appear in the context menu. Contexts can be added by calling context.add() and removed by called context.remove().

parentMenu

The item's parent Menu, or null if the item is contained in the top-level context menu. This property is read-only. To add the item to a new menu, call that menu's addItem() method.

contentScript

The content script or the array of content scripts associated with the menu item during creation.

contentScriptFile

The URL of a content script or the array of such URLs associated with the menu item during creation.

Events

message

If you listen to this event you can receive message events from content scripts associated with this menu item. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the menu item's message event.

Arguments

value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value.

A labeled menu item that expands into a submenu.

Methods

addItem(item)

Appends a menu item to the end of the menu. If the item is already contained in another menu or in the top-level context menu, it's automatically removed first. If the item is already contained in this menu it will just be moved to the end of the menu.

Parameters

item : Item,Menu,Separator
The Item, Menu, or Separator to add to the menu.

removeItem(item)

Removes the given menu item from the menu. If the menu does not contain the item, this method does nothing.

Parameters

item : Item,Menu,Separator
The menu item to remove from the menu.

destroy()

Permanently removes the menu from its parent menu and frees its resources. The menu must not be used afterward. If you need to remove the menu from its parent menu but use it afterward, call removeItem() on the parent menu instead.

Properties

label

The menu's label. You can set this after creating the menu to update its label later.

items

An array containing the items in the menu. The array is read-only, meaning that modifications to it will not affect the menu. However, setting this property to a new array will replace all the items currently in the menu with the items in the new array.

image

The menu's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI. You can set this after creating the menu to update its image later. To remove the menu's image, set it to null.

context

A list of declarative contexts for which the menu will appear in the context menu. Contexts can be added by calling context.add() and removed by called context.remove().

parentMenu

The menu's parent Menu, or null if the menu is contained in the top-level context menu. This property is read-only. To add the menu to a new menu, call that menu's addItem() method.

contentScript

The content script or the array of content scripts associated with the menu during creation.

contentScriptFile

The URL of a content script or the array of such URLs associated with the menu during creation.

Events

message

If you listen to this event you can receive message events from content scripts associated with this menu item. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the menu item's message event.

Arguments

value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value.

Separator

A menu separator. Separators can be contained only in Menus, not in the top-level context menu.

Methods

destroy()

Permanently removes the separator from its parent menu and frees its resources. The separator must not be used afterward. If you need to remove the separator from its parent menu but use it afterward, call removeItem() on the parent menu instead.

Properties

parentMenu

The separator's parent Menu. This property is read-only. To add the separator to a new menu, call that menu's addItem() method.

文件標籤與貢獻者

 此頁面的貢獻者: shyangs
 最近更新: shyangs,