Port error: Could not establish connection. Receiv

2019-01-18 01:42发布

问题:

I'm developing an extension in Chrome, and there's a problem. In my inject.js, I make a request like:

chrome.extension.sendRequest({command:'skip'},callback)

and in my `background.js I simply add a request Listener like:

chrome.extension.onrequest.addListener(function(req,sender,res){console.log("procession"})

But there's an error:

Port error: Could not establish connection. Receiving end does not exist

It seems a bug in chrome? PS:
part of my manifest.json

"background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {
      "matches": ["&lt all_urls &gt"], 
      "js": ["inject.js"]
    }
  ],

I'm in Chromium 17, and I tried reloading the extension, reopening the browser... nothing happened
some one get some ideas?

回答1:

I found myself having the same issue as you describe here. The solution I found that works for me is to use a backgroundpage instead of a background script, like so:

"background_page": "src/background.html",
  // maybe this seems to work instead of background { scripts [] }

  /* this gives a Port error: Could not ...
  "background": {
  "scripts": ["src/background.js"]
  },
  */

I hope this works for you too.



回答2:

This isn't always the cause, but if you have an error in your background.js, you should check this link:

Inspect views: _generated_background_page.html

in the Extensions page, which will show you any JavaScript errors.

This was preventing my connections from getting established.



回答3:

The problem could be that sendRequest() and onRequest have been deprecated and replaced with sendMessage() and onMessage. Since a recent Chrome 20 update they seem to be gone completely.

The official documentation on Message Passing doesn't even mention sendRequest() anymore.

Here is a link which documents the change a little bit: http://codereview.chromium.org/9965005/



回答4:

An HTML background page didn't work for me in Chrome 20.0.1132.57 m on Windows 7 with the same error:

Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:232

I tried using a background.js script with the following content:

chrome.extension.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(msg) {
        // May be empty.
    });
});

That solved the immediate onDisconnect in my content script:

port = chrome.extension.connect();
port.onDisconnect.addListener(function (event) {
    // Happened immediately before adding the proper backend setup.
    // With proper backend setup, allows to determine the extension being disabled or unloaded.
});

The correct code came from Chromium Extensions messaging example: http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/messaging/timer/page.js?view=markup

The example also contains the second part that serves as a backend for sendRequest, but I haven't tested it myself:

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        // Don't know if it may be empty or a sendResponse call is required.
    });


回答5:

After some time spent on investigation I found the problem in my case.

I'm also getting:

Port error: Could not establish connection. Receiving end does not exist. 

Before explaining, I want to say that I'm using sendMessage and onMessage for communication.

For me this error appear when I'm sending a message from the background page to one tab where my content script is running.

My extension runs only on tabs where youtube is open. So when I'm changing some preferences I'm looking to see what tabs I have open and send a message to update updated preference.

In a normal case it works fine, but if I have n (n >= 1) tabs with youtube open. I click in "Reload" button for extension, I change something ... youtube tabs are not refreshed and they lost message listener so I'm getting this error.

It seems that is pretty normal.

If I refresh youtube tabs after extension reload I don't get this error.

I found one solution, it may not apply for all cases:

When I had this issue my code was:

chrome.tabs.sendMessage(tabId, {proprName: proprName, newValue: newValue}, function(response) {});

Now my code is:

chrome.tabs.sendMessage(tabId, {proprName: proprName, newValue: newValue});

For my I didn't needed response callback and because that was not responding I had this error.



回答6:

I'm using sendMessage and onMessage for communication too, and in my workflow I first send a message from injected.js to my background.js and I also got "Port error: Could not establish connection. Receiving end does not exist." error.

So I decided to deal with using the responses functionalities ( like ACK ), and if background doesn't respond I keep trying with a setTimeout like so.

//background.js

...
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
...
//some code

sendResponse({status: 'everything ok'})
return true;    
});

//injected.js

var myInjectedFunctionality = function() {

    chrome.extension.sendMessage({method: "Steroids:loadScripts"}, function(res) {
        if(res && res.status) {
            } else {
                setTimeout(myInjectedFunctionality, 3000);
            }
    });
};
myInjectedFunctionality();

My code is now running properly so I think that the explanation is easy to view. Chrome don't prepare Background.js and connection stuffs when it inject your code in the pages where you want to, and so makes nobody listen for your sent message, so if no one is listening, just keep trying like I do.



回答7:

try to inject some contect scripts into a tab which url is chrome://* or https://chrome.google.com/* , when connect these tabs in backgroundpage ,

for example

chrome.tabs.connect(tab.id).postMessage(msg)

then will throw

Port error: Could not establish connection. Receiving end does not exist.

these page not allow inject content scripts, and the connection will disconnect immediately .

so, check the url and not connect these tabs ,then the exception is not thrown



回答8:

Check the latest manuals: http://developer.chrome.com/extensions/messaging.html

Note: If multiple pages are listening for onMessage events, only the first to call sendResponse() for a particular event will succeed in sending the response. All other responses to that event will be ignored.

Close your tabs, leave only one page, and check. In my case this was the issue.



回答9:

Confronting with the same issue now.

//Here is my former background.js:

chrome.runtime.onInstalled.addListener(function () {
  //some other code here
  chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.url) {
        chrome.downloads.download({
            url: message.url,
            conflictAction: 'uniquify',
            saveAs: false
        });
    }
});});//(Sorry, I tried but failed to put the last bracket on next line)

You see, the chrome.runtime.onMessage.addListener is fired when the event onInstalled happpens, and when I get it out of this scope, and make my code like this:

chrome.runtime.onInstalled.addListener(function () {
  //some other code here
});  
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.url) {
        chrome.downloads.download({
            url: message.url,
            conflictAction: 'uniquify',
            saveAs: false
        });
    }
});

It works well now. Hope to be helpful.



回答10:

If you get the problem, mostly because you are referring the outdated document, update it!

Visit: chrome extension: messaging.html



回答11:

I was seeing this problem, where my content script wasn't loading, so posting a message was never happening.

The problem turned out to be that I had the background script inspector open and was just pushing Cmd+R (refresh), but there was a bug in my manifest.json. When I actually went to the extensions page and reloaded that page, I got the alert showing the manifest error.

Basically, I saw this because my content scripts never loaded in the first place and I thought I was refreshing my manifest, but I wasn't.



回答12:

I was seeing this error using manifest_version: 2 and chrome.runtime.sendMessage. I am connecting from a web page to the extension instead of within the extension.

The solution was to make sure I had the correct values in the externally_connectable.matches array in manifest.json. You need to list the URLs that you want to be able to connect to the extension. See https://developer.chrome.com/extensions/manifest/externally_connectable#without-externally-connectable.