Reputation: 133
I am trying to sendMessage from my contextmenu.js file to my content.js file anytime the user right clicks on any website on chrome.
This will include sites
- that are on the current tab and is active
- that are popups and is inactive
- that are popups and is active
- on another window and is inactive
- on another window and is active
My code looks like this:
//contextmenu.js
chrome.contextMenus.onClicked.addListener((clickData, tab) => {
chrome.tabs.sendMessage(tab.id, {text: 'rightClicked'}, (response) => {
console.log(response)
})
})
//content.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.text === 'rightClicked') {
sendResponse('performing operation')
}
})
I'm getting the error message:
"Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist."
Upvotes: 0
Views: 103
Reputation: 133
I figured it out.
There is nothing wrong with my code. I was just not matching the right URLs, because I was testing the onClick on a blank page which has no URL or chrome://extension itself. The code works on a any website.
//manifest.json
"content_scripts": [
{
"matches": ["<all_urls>"]
...
}
Upvotes: 0
Reputation: 73506
Assuming contextmenu.js
is declared in "background"
section and content.js
in "content_scripts"
section of manifest.json, the posted code is fine, but extensions have many moving parts so the problem is elsewhere. The error message means there was no content script running at the time the message was sent, which could happen in these cases:
"run_at": "document_start"
in manifest.json's content_scripts
section, more info.content_scripts
section in manifest.json, more info.you clicked inside an iframe but you didn't allow the content script to run inside iframes - add "all_frames": true
in manifest.json's content_scripts
section, more info and specify frameId in sendMessage like this:
chrome.contextMenus.onClicked.addListener((clickData, tab) => {
const {frameId} = clickData;
chrome.tabs.sendMessage(tab.id, {text: 'rightClicked'}, {frameId}, response => {
console.log(response)
});
});
the page can't run content scripts at all (e.g. a chrome:// page or another extension) - can't be fixed in general but for a personal use you can start Chrome with --extensions-on-chrome-urls
command line switch and add chrome://*/*
pattern to the content_scripts
section's matches
list.
chrome://policy
for the presence of runtime_blocked_hosts
and contact your adminUpvotes: 1