Connect C++ native app to Firefox WebExtensions add-on with native messaging

吃可爱长大的小学妹 提交于 2020-01-05 02:36:28

问题


I want to make a easy example Firefox add-on using Native messaging. Here is my code:

Native App:

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 code:

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");
});

When I added the add-on to Firefox, I got 2 errors:

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

(Don't have native-messaging tag. So, I used chrome-native-messaging tag, but I want to make this sample run on Firefox)

EDIT1:

This 2 errors is my mistake. I just remove 'python' on ping_pong_win.bat to solved them.

But I got another problem. When I run this test, this is result:

Sending:  ping
Received: [object Object]

Seem like native app doesn't work.

EDIT2: I debugged, Native app got "ping" message but It can't send the response "pong" message

Solved: Native app sent response to browser, I just print wrong: @@

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

来源:https://stackoverflow.com/questions/42384875/connect-c-native-app-to-firefox-webextensions-add-on-with-native-messaging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!