MenuEvent.source

By Opera Software

From Opera 15 onward, Opera 11 & 12’s extension format is no longer supported, and instead, we’ve switched to Chromium’s extension model. Check out our new documentation for developing extensions for Opera 15 and higher and start building your own extensions.

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);
})();

This article is licensed under a Creative Commons Attribution 3.0 Unported license.

Comments

No new comments accepted.