Chrome message passing error : Attempting to use a disconnected port object

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

My chrome extension uses long-lived 'Port' object for message passing between 'content script' and 'popup' page. The 'popup' is able to send a message to the 'content script' event listener. But, the 'Port' object in the 'content script' is unable to send message to the 'popup' page.

var port = chrome.extension.connect({"name":"swap"});  // listener for incoming connections chrome.extension.onConnect.addListener(function( incomingPort ){      // listener on incoming messages     incomingPort.onMessage.addListener(function( msg ){          if( msg.command === 'get_scripts' ){             //do work          }          var scrs = { 'scripts' : 'name' };         var result = port.postMessage( scrs );      }); }); 

When executing 'port.postMessage(Object obj)' , the plugin throws the following Error,

Error in event handler for 'undefined': Attempting to use a disconnected port object   Error: Attempting to use a disconnected port object at PortImpl.postMessage (miscellaneous_bindings:54:5) at chrome-extension://loiamkgdhfjdlkcpehnebipeinpcicfj/swap.js:27:31 at [object Object].dispatch (event_bindings:203:41) at Object.<anonymous> (miscellaneous_bindings:250:22) event_bindings:207 

I have tried using 'Port' object and 'incomingPort' object, both throw the same 'Error'. It feels like it has to do with the scope of the pre-created 'Port' object.

The plugin code is available at this git repository https://github.com/snambi/chrome_plugin/tree/master/src/chrome

What is wrong in this plugin?

回答1:

I've looked through your code, and it makes no sense to me:

  • Did you know that a port has an onMessage and postMessage method at both sides? One single port is sufficient to communicate in both directions.
  • Communicating between a popup and a content script in your way is going to be terribly hard. It's hard to launch the content script and the pop-up simultaneously.

Since your extension has no background page, and a relatively useless content script, I assume that your extension's core is the browser action popup window. Instead of injecting a content script by default, you can also use the following flow:

  1. User clicks on browser action
  2. popup.html and popup.js are executed.

I've also seen that you're using port == null to check whether a port valid or not. If you do that, make sure that the comparison makes sense, by voiding the variable when the port is disconnected:

var port; chrome.runtime.onConnect.addListener(function(_port) {     // ...optional validation of port.name...      port = _port;     port.onMessage.addListener(function(message) { /* .. logic .. */});     port.onDisconnect.addListener(function() {         port = null;     }); }); 


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