ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] > [参考](http://blog.haoji.me/chrome-plugin-develop.html#chang-lian-jie-he-duan-lian-jie) ## 长连接和短连接 Chrome插件中有2种通信方式, - 一个是短连接(chrome.tabs.sendMessage和chrome.runtime.sendMessage) - 一个是长连接(chrome.tabs.connect和chrome.runtime.connect) 而长连接类似WebSocket会一直建立连接,双方可以随时互发消息 ## 示例 ### 长连接 popup.js: ``` getCurrentTabId((tabId) => { var port = chrome.tabs.connect(tabId, {name: 'test-connect'}); port.postMessage({question: '你是谁啊?'}); port.onMessage.addListener(function(msg) { alert('收到消息:'+msg.answer); if(msg.answer && msg.answer.startsWith('我是')) { port.postMessage({question: '哦,原来是你啊!'}); } }); }); ``` content-script.js: ``` // 监听长连接 chrome.runtime.onConnect.addListener(function(port) { console.log(port); if(port.name == 'test-connect') { port.onMessage.addListener(function(msg) { console.log('收到长连接消息:', msg); if(msg.question == '你是谁啊?') port.postMessage({answer: '我是你爸!'}); }); } }); ```