google-chrome-extension - connectNative 在 Chrome 扩展程序中自行断开连接

标签 google-chrome-extension chrome-native-messaging

我确实写了一个 chrome 扩展。我的内容脚本通过 background.js 发送一些数据。我的 background.js shell 将此数据转发到本地 C++ 应用程序。 现在发生的是,我的 background.js 可以连接到本地应用程序并发送一次数据。但是随后,连接断开,因为断开连接事件发生并且第二个发送请求失败。阅读 connectNative 的文档,它说,如果调用 disconnect“当包含端口的页面被卸载时”,连接将关闭。我的代码中根本没有断开连接,并且 background.js 不应卸载,因为根据文档 background.js 的实时时间与扩展名。 使用我的代码,测试 1 和测试 2 在目标文件 Test.txt 中到达一次,但第二次发送失败,因为两者之间的连接丢失。

这里是代码。

背景.js:

var port = null;
var firstTime;

function onNativeMessage(message) {
    console.log("Native Message received: " + message);
}

function onDisconnected() {
    console.log("Disconnected");
    //port = null;
}

function connect() {
    console.log("Connect");
    //port = chrome.extension.connectNative('chromeinterface');
    port = chrome.runtime.connectNative('chromeinterface');
    port.onMessage.addListener(onNativeMessage);
    port.onDisconnect.addListener(onDisconnected);
}

chrome.extension.onRequest.addListener(function(data, sender) {
    if(firstTime !== 'xdefined') {
        firstTime = 'xdefined';
        connect();
    }

    port.postMessage("Test 1");
    port.postMessage("Test 2");
    console.log("Send");
}
});

list .json:

{
  "name": "Test",
  "version": "1.0",
  "description": "Test native messaging",

  "background": {
  "scripts": ["background.js"]
  },

  "content_scripts": [
   {
     "matches": ["<all_urls>"],
     "js": ["contentscript.js"]
   }
  ],

  "permissions": ["tabs", "nativeMessaging", "<all_urls>"],

  "manifest_version": 2
}

chromeinterface.json:

{
 "name": "chromeinterface",
 "description": "Chrome Native Messaging API Example Host",
 "path": "chrome_interface",
 "type": "stdio",
 "allowed_origins": [
   "chrome-extension://abc.../"
 ]
}

chrome_interface.cpp:

...
using namespace std;

void StoreData(string data)
{
   ofstream File;
   File.open("Test.txt", ios_base::out|ios_base::app);
   if (File.is_open())
   {
      File << data;
      File.close();
   }
}

int main(int argc, char* argv[])
{
    std::cout.setf( std::ios_base::unitbuf ); 
    unsigned int a, c, i, t=0;
    std::string inp;  
    bool bCommunicationEnds = false;

    StoreData("Start " + inp + "\n");
    cout << "Start" << endl;

    do {

        inp="";
        t=0;
        // Sum the first 4 chars from stdin (the length of the message passed).
        for (i = 0; i <= 2; i++) {
            t += getchar();
        }

        // Loop getchar to pull in the message until we reach the total
        //  length provided.
        for (i=0; i < t; i++) {
            c = getchar();
            if(c == EOF)
            {
                bCommunicationEnds = true;
                i = t;
            }
            else
            {
                inp += c;
            }
        }
        StoreData("Received " + inp + "\n");

        if(!bCommunicationEnds)
        {
            //Collect the length of the message
            unsigned int len = inp.length();
            //// We need to send the 4 btyes of length information
            std::cout << char(((len>>0) & 0xFF))
                << char(((len>>8) & 0xFF))
                << char(((len>>16) & 0xFF))
                << char(((len>>24) & 0xFF));
            //// Now we can output our message
            std::cout << inp;
        }
    }while(!bCommunicationEnds);

    StoreData("Com end\n");

    return 0;
}

控制台日志:

Connect
Send
Disconnected
Error in event handler for extension.onRequest: Attempting to use a disconnected port object 

最佳答案

删除 cout << "Start" << endl;从你的代码。 native 消息传递通过标准输入和标准输出进行通信。如果您在 stdout 中插入任何其他垃圾,则会违反协议(protocol),Chrome 将终止 native 应用程序。

除此之外,下面的内容看起来不像是“读取 4 个字符”,而是“读取 3 个字符”。

    // Sum the first 4 chars from stdin (the length of the message passed).
    for (i = 0; i <= 2; i++) {
        t += getchar();
    }

即使在更改 i <= 2 之后至 i < 4 ,这仅适用于最多 255 个字节的消息,因为您要对各个字节求和,而不是将四个字节解释为一个整数。我建议将之前的代码片段替换为:

    unsigned int t;
    std::cin.read(reinterpret_cast<char*>(&t), sizeof(t));

从终端启动 Chrome 并查看终端内的标准输出以获得更多有用的错误以调试 native 应用程序。

关于google-chrome-extension - connectNative 在 Chrome 扩展程序中自行断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24775096/

相关文章:

javascript - 从元素列表优化音频预加载

javascript - HTML/JS 代码可以在普通浏览器 View 中运行,但无法作为 Chrome 扩展运行?

java - Chrome 应用程序 : Launch a external application (shell script or jar) using native messaging hosts

c++ - 收到 native 消息,但响应失败

java - 如何在java中实现chrome原生消息处理协议(protocol)

javascript - 检查 Chrome 扩展的元素?

google-chrome-extension - CHROME WebRequest API 示例错误 : "onBeforeRequest" can only be used in extension processes

google-chrome-extension - Chrome 扩展问题(无效 list )

javascript - 为 Chrome 扩展程序指定 native 消息传递主机

macos - 连接失败 : Native host has exited