2016-05-16 50 views
0

當我點擊我的開發/面板界面中的按鈕時,我需要調用高級API函數。我這樣實現它。 當addon處於onReady狀態時,addon將postMessage發送到panelSide。firefox插件和開發/面板之間的通信

// index.js 
onReady: function() { 
    // in this function you can communicate 
    // with the panel document 
    this.postMessage("add-on-ready", [panelSide]); 
    //this.postMessage("add-on-ready2", [panelSide]); // This message may be received in logic-panel.js 
} 

主機將在textarea的添加所接收的消息和只需按某個按鈕回覆插件:

//logic-panel.js 
window.addEventListener("message", function(event) { 
    var toAddon = event.ports[0]; 
    toAddon.start(); 

    $(document).ready(function(){ 
     $('#log').append(event.data + '\n'); 
    }); 

    switch(event.data){ 
     case "add-on-ready": 
      $(document).ready(function(){ 
       $("#inspect").click(function(){ 
        toAddon.postMessage("inspect"); 
       }); 
       $("#exit").click(function(){ 
        toAddon.postMessage("exit"); 
       }); 

      }); 
      break; 

     default: 
      toAddon.postMessage("event.data = " + event.data); 
      alert("event.data = " + event.data); 
    } 
}); 

附加組件處理響應。如果按鈕「考察」被按下,然後將參與高層次的API(即PageMod在handleClick功能):

//index.js 
addonSide.onmessage = function(event) { 
    console.log(event.data); 
    switch(event.data){ 
     case "inspect": 
      console.log("run inspect"); 
      handleClick(); 
      console.log("run inspect end"); 
      break; 

     case "exit": 
      console.log("push exit =("); 
      break; 

     default: 
      MyPanel.postMessage("add-on-ready", [panelSide]);  //not work 
    } 
} 


function handleClick() { 
    console.log("xpath"); 
    var data = require("sdk/self").data; 

    var pageMod = require('sdk/page-mod').PageMod({ 
     include: ['*'], 
     contentScriptFile: data.url("./addonside/xpath.js"), 
     onAttach: function(worker) { 
      worker.on('message', function(message) { 
       console.log('mouseclick: ' + message); 
       //////////////////////////////// 
       // this.postMessage('mouseclick: ' + message, [panelSide]); // This message not may be received in logic-panel.js 
       //////////////////////////////// 
      }); 
     } 
    }); 
} 

問:我如何發送的postMessage到面板handleClick()函數?也許有更合適的方式使用dev/panel調用高級API?

回答

0

在index.js聲明var _MyPanel;

onReady

onReady: function() { 
    _MyPanel = this; 
    _MyPanel.postMessage("add-on-ready", [panelSide]); 
} 

而且handleClick()

function handleClick() { 
    console.log("xpath"); 

    var data = require("sdk/self").data; 

    var pageMod = require('sdk/page-mod').PageMod({ 
     include: ['*'], 
     contentScriptFile: data.url("./addonside/xpath.js"), 
     onAttach: function(worker) { 
      worker.on('message', function(message) { 
       console.log('mouseclick: ' + message); 
       _MyPanel.postMessage("mouseclick: " + message, [panelSide]); 
      }); 
     } 
    }); 
}