Source

swaplang / index.html

<!DOCTYPE html>
<head>
<meta name="Content-Type" content="text/html; charset = UTF-8">
<title>Swaplang background page</title>
<style>
  body {width:1000px}
  :link {text-decoration:none}
  a:hover {background: #ddd;}
  * {margin: 0px ; padding: 0px; line-height:1em}
  p { line-height: 1.4em}
  li { font-family: sans-serif; margin-left: 16px; line-height:1.1em}
</style>
</head>
<body>
<ul><li id="item">dummy</li></ul>

<script>

  var UIItemProperties = {
    disabled: true,
    title: "Change Languages",
    icon: "icno.png",
    popup: {
      href: "popup.html",
      height: 10, width: 10
    }
  }
  theButton = opera.contexts.toolbar.createItem(UIItemProperties);
  opera.contexts.toolbar.addItem(theButton);

  function enableButton(){
    theButton.icon = "icon.png";
    theButton.disabled = false;
  }
  function disableButton(){
    theButton.disabled = true;
    theButton.icon = "icno.png";
  }

  //Always disable the button on blur or loading a new page
  opera.extension.tabs.onblur = disableButton;

  //Onfocus, demand that the userJS report if there are language choices
  opera.extension.tabs.onfocus = opera.extension.windows.onfocus = requestChoices;

  function requestChoices() {
    var currentTab = opera.extension.tabs.getFocused();
    if (currentTab) {
      currentTab.postMessage("reportLangChoices");
    }
  }
  
  //------------------------------------
  opera.extension.onmessage = function( event ){
    if (event.data == "none") 
      disableButton();
    else if (event.data == "ready") 
      requestChoices();
    else {
    // The current tab is sending a menu to the popup.
    // Use the info given to set the popup size and enable the button.
      var theInfo = JSON.parse(event.data);
      var theSpan = document.createElement('span');
      theSpan.innerText = theInfo.longestString;
      document.getElementById('item').appendChild(theSpan);
      var baseWidth = theSpan.offsetWidth;
      var theSize = theSpan.currentStyle["fontSize"];
      var baseHeight = parseInt(theSize.substring(0,theSize.indexOf('px')));

      theButton.popup.height = ((1.15 * theInfo.languagesAvailable + 1.5) * baseHeight);
      theButton.popup.width = baseWidth + 16;
      enableButton();
    }
  }

  //If a popup connects, forward a port to current tab for the menu
  opera.extension.onconnect = function( event ){
    var currentTab = opera.extension.tabs.getFocused();
    if (currentTab && event.origin.indexOf("popup.html") > -1 && event.origin.indexOf('widget://') > -1) {
      currentTab.postMessage( "setupChannel", [event.source] );
    }
  }
  //------------------------------------
</script>