在Firefox附加内容脚本中接收来自main.js的消息

时间:2015-06-05 17:23:56

标签: javascript firefox firefox-addon firefox-addon-sdk

我正在尝试在main.js和内容脚本之间进行通信。这是我的main.js

var pageMod = require('sdk/page-mod');
var self = require('sdk/self');
var ss = require('sdk/simple-storage');

pageMod.PageMod({
    include: 'example.com',
    contentScriptFile: self.data.url('content-script.js'),
    onAttach: function(worker) {
        worker.port.on('getSetting', function(request) {
            // var settingValue = ss.storage[request]
            var settingValue = 'test value'; // for testing, return an 
                                             // arbitrary string
            worker.port.emit('settingRetrieved', settingValue);
        });
    }
});

content-script.js

alert('getting setting...');
self.port.emit('getSetting', 'test setting name');
alert('asked for setting...');
self.port.on('settingRetrieved', function(results) {
    alert('retrieved setting: "' + results + '"');
});

self.port.on()中的content-script.js似乎未收到来自main.js的消息。我做错了什么?

1 个答案:

答案 0 :(得分:2)

捂脸。来自content-script.js的代码包含在jQuery事件处理程序中,因此self.port.on()无法正常侦听。

以下是工作代码 - 首先是main.js

var pageMod = require('sdk/page-mod');
var self = require('sdk/self');
var ss = require('sdk/simple-storage');

pageMod.PageMod({
    include: 'example.com',
    contentScriptFile: self.data.url('content-script.js'),
    onAttach: function(worker) {
        worker.port.on('getSetting', function(request) {
            var settingValue = ss.storage[request];
            worker.port.emit('settingRetrieved',
                {
                    'settingName': request,
                    'settingValue': settingValue,
                }
            );
        });
    }
});

content-script.js

// Store the setting value
var mySetting = '';

// Listen for retrieval the setting value
self.port.on('settingRetrieved', function(results) {
    mySetting = results['settingValue'];
});

// Generic function to retrieve a setting value
function getSetting(setting) {
    self.port.emit('getSetting', setting);
}

// Retrieve the value of 'mySetting' and do something with it
$(document).ready(function() {
    $('#my-element').click(function() {
        getSetting('mySetting');
        /*
        ...
        Value of mySetting has been updated; do something with it here
        ...
        */
    });
});