Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

7,879 views
Skip to first unread message

Morten Overgaard

unread,
Mar 18, 2022, 5:47:13 PM3/18/22
to Chromium Extensions
Situation:
Inject.js is injected into the page's MAIN world using chrome.scripting.executeScript from background.js

Everything works as expected except when trying to send a message from inject.js  back to extension.

The message actually hits the target but always followed by the error

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.


// inject.js
chrome.runtime.sendMessage("<extensionId>","Test", (resp => {
console.log(resp);
res("OK");
}));

The same happens when trying the below - any idea why ??
 chrome.runtime.connect(<extensionid>,{});

br Morten

Stefan vd

unread,
Mar 19, 2022, 5:47:35 AM3/19/22
to Chromium Extensions, overgaa...@gmail.com
Hi br,

Do you have this issue also with this sample code (manifest v3)? That with this background listener:
background.js
// Example of a simple user data object
const user = {username: 'demo-user'};
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// 2. A page requested user data, respond with a copy of `user`
if (message === 'get-user-data') {
sendResponse(user);
}
});

inject.js
// 1. Send the background a message requesting the user's data
chrome.runtime.sendMessage('get-user-data', (response) => {
  // 3. Got an asynchronous response with the data from the background
  console.log('received user data', response);
  initializeUI(response);
});

Thanks,
Stefan vd

Morten Overgaard

unread,
Mar 19, 2022, 5:57:31 AM3/19/22
to Chromium Extensions, Stefan vd, Morten Overgaard
I have no problems when using runtime.sendMessage from  a "normal" content script - everything is all god.

// background.js
...
let resp = chrome.scripting.executeScript({
target: { tabId: t.id},
files : ["./extension/src/inject.js"],
world: "MAIN",
}); 


Its when inject.js gets injected into the page's main world context the error occurs
calling runtime.sendMessage from inside inject.js fails with the error.

makes sense ? 

wOxxOm

unread,
Mar 19, 2022, 10:08:44 AM3/19/22
to Chromium Extensions, overgaa...@gmail.com, Stefan vd
To receive messages from the page you need to use a different event: chrome.runtime.onMessageExternal and declare externally_connectable in manifest.json, see the documentation: https://developer.chrome.com/extensions/messaging#external-webpage

wOxxOm

unread,
Mar 19, 2022, 10:11:26 AM3/19/22
to Chromium Extensions, wOxxOm, overgaa...@gmail.com, Stefan vd
BTW if you only send a single message, you can simply return a Promise as the last evaluated expression in the script instead of messaging, which will be transferred to the result of executeScript.
Reply all
Reply to author
Forward
0 new messages