Sending information to the content script for a context-menu

后端 未结 1 1488
粉色の甜心
粉色の甜心 2021-01-13 20:35

I\'ve seen many questions regarding context-menu and two-way communication and it appears that I know the answer to my question... \"you can\'t\", but I\'m going to try any

相关标签:
1条回答
  • 2021-01-13 21:14

    Thank you to Wladimir! The following code does what I want it to:

    In the main.js for the context-menu:

    myAppContextMenu = contextMenu.Item({
        label: "Translate Selection",
        context: contextMenu.SelectionContext(),
        contentScriptFile : [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppcontextmenu.js')],
        onMessage: function (data) {
            var text = require('selection').text;
            require('request')
                .Request({
                    url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
                    content: {
                        appid : 'myappid',
                        to : data.to,
                        from : data.from,
                        text : text
                    },
                    onComplete: function (response) {
                        var index,
                            tabs = require('sdk/tabs');
    
                        for (index = 0; index < workers.length; index += 1) {
                            if (workers[index].tab === tabs.activeTab) {
                                workers[index].port.emit('selectionTranslation', { text: text, response : response.text, leftOffset : data.leftOffset, topOffset : data.topOffset });
                            }
                        }
                    }
                })
                .get();
        }
    });
    

    and in the content script:

    self.on(
        'click',
        function (node, data) {
            'use strict';
            var selectedElement = $(node),
                messageData =
                    {
                        to : 'es',
                        from : 'en',
                        topOffset : selectedElement.offset().top + (selectedElement.height() / 2),
                        leftOffset : selectedElement.offset().left + (selectedElement.width() / 2)
                    };
    
            self.postMessage(messageData);
        }
    );
    

    There is a global workers array variable defined in the exports.main function that gets populated by the onAttach function of the page mod as so:

            workers.push(worker);
    
            worker.on(
                'detach',
                function () {
                    var index = workers.indexOf(worker);
                    if (index >= 0) {
                        workers.splice(index, 1);
                    }
                }
            );
    
    0 讨论(0)
提交回复
热议问题