Developers › Dev.Opera

MenuEvent.source

August 24, 2012 · by Opera Software

This functionality has not landed in a stable Opera version yet, but you can use it already in Opera Next.

Description:

The source attribute is a MessagePort to the current BrowserTab object in which the current event was fired. If the event was fired in an injected script this attribute will be null (default).

Syntax:

readonly MessagePort source

Example:

In this example, a menu item is added to the context menu for selected text only. When the menu item is clicked, the selected text is sent to an injected script in the current tab. The selected text is then reversed and shown in a popup alert box.

<!-- 
  The configuration file ('config.xml').
-->
<?xml version='1.0' encoding='utf-8'?>
<widget xmlns="http://www.w3.org/ns/widgets">
    ...
    <feature name="opera:contextmenus"/>
    ...
</widget>
//
// The background process (e.g. '/background.js'). 
//

if (opera.contexts.menu) {
  var menu = opera.contexts.menu;
  
  // Create a menu item properties object
  var itemProps = {
    contexts: ['selection'],
    title: 'Reverse text',
    onclick: function(event) {
      // Send the selected text to the originating tab
      event.source.postMessage({query: event.selectionText});
    }
  }

  // Create a menu item with the specified properties
  var item = menu.createItem(itemProps);
  // Add the menu item to the context menu
  menu.addItem(item);
}
//
// An injected script (e.g. '/includes/injected.js').
//

(function() {
  // Source: http://4umi.com/web/javascript/reverse.php
  String.prototype.reverse = function() {return this.split('').reverse().join('');};

  // Listen for a message from the background process
  opera.extension.addEventListener('message', function(event) {
    // Get the selected text from the event's data object
    alert(event.data.query.reverse());
  }, false);
})();

About this article

Published inDev.Opera
DateAugust 24, 2012
AuthorOpera Software
Tagscontext menu, extensions API
OriginalInternet Archive