将C ++本机应用程序连接到具有本机消息传递的Firefox WebExtensions附加组件

时间:2017-02-22 07:11:28

标签: c++ firefox-addon firefox-webextensions chrome-native-messaging

我想使用Native消息传递一个简单的Firefox插件示例。这是我的代码:

原生应用

void SendDataToExtension(string message)
{
    _setmode(_fileno(stdout), O_BINARY);
    try {
        unsigned int len = message.length();
        std::string message = "{\"text\": \"This is a response message\"}";
        unsigned int lenStr = str.length();
        std::cout << char(((lenStr >> 0) & 0xFF))
            << char(((lenStr >> 8) & 0xFF))
            << char(((lenStr >> 16) & 0xFF))
            << char(((lenStr >> 24) & 0xFF));
        std::cout << str.c_str();
        std::cout.flush();
    }
    catch (...) {
        throw;
    }
}

string OpenStandardStreamIn()
{
    std::cout.setf(std::ios_base::unitbuf);
    _setmode(_fileno(stdin), _O_BINARY);
    unsigned int c, t = 0;
    size_t pos = 0, m = 0;
    std::string inp;
    inp = "";
    t = 0;
    for (int i = 0; i <= 3; i++) {
        t += (unsigned int)pow(256.0f, i) * getchar();
    }
    for (int i = 0; i < (int)t; i++) {
        c = getchar();
        inp += c;
    }
    return inp;
}

int _tmain(int argc, _TCHAR* argv[])
{
    string input = "";
    while ((input = OpenStandardStreamIn()) != "")
    {
        try 
        {
            if (input.compare("ping")) {
                SendDataToExtension("pong");
            }
        }
        catch (...) { throw; }
    }
    return 0;
}

JS代码:

var port = browser.runtime.connectNative("ping_pong");

port.onMessage.addListener((response) => {
  console.log("Received: " + response);
});

browser.browserAction.onClicked.addListener(() => {
  console.log("Sending:  ping");
  port.postMessage("ping");
});

当我将附加组件添加到Firefox时,我遇到了2个错误:

stderr output from native app ping_pong:   File "ping_pong.exe", line 1

stderr output from native app ping_pong: SyntaxError: Non-ASCII character '\x90' in file ping_pong.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

(没有原生信息标签。所以,我使用了chrome-native-messaging标签,但我想让这个示例在Firefox上运行)

EDIT1:

这2个错误是我的错误。我只是删除ping_pong_win.bat上的'python'来解决它们。

但是我遇到了另一个问题。当我运行此测试时,结果如下:

Sending:  ping
Received: [object Object]

看起来像本机应用程序不起作用。

EDIT2: 我调试,Native应用程序收到“ping”消息,但它无法发送响应“pong”消息

解决: 本机应用程序向浏览器发送了响应,我只是打印错误:@@

port.onMessage.addListener((response) => {
  console.log("Received: " + response.text);
});

0 个答案:

没有答案