I am new to Chrome extension, I tried to write a test extension, the messaging between the popup page and background page works as expected, but when I try to send message from popup to content script, there is always the error "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.", this may means there is no registered listener. I check the code again and again in the popup and content script files, but can't find where is wrong. Thank you for help!
Here are the files:
manifest.json:
{
"manifest_version": 2,
"name": "Chrome extension test 01",
"description": "test extension messaging",
"version": "1.0.0.0",
"permissions": [ "tabs", "activeTab", "https://*/*", "http://*/*"],
"icons": {
"128": "images/icon128.png"
},
"browser_action": {
"default_title": "Here is the extension icon title",
"default_popup": "popup.html",
"default_icon": {
"16": "images/icon16.png",
"32": "images/icon32.png",
"48": "images/icon48.png"
}
},
"content_scripts":
[
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
}
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Test extension for chrome</title>
</head>
<body>
<h3>Chrome extension messaging test</h3>
<div>
<!-- Display message sent from backgroud: "This is the message sent from the background" -->
<p id="showMsg"></p>
</div>
<h2 id="test02">click to test messaging (content script)</h2>
<script ype="text/javascript" src="popup.js"></script>
</body>
</html>
popup.js
//popup.js
document.addEventListener('DOMContentLoaded', function(){
chrome.runtime.sendMessage({greeting: "hello"}, function(response){
console.log(response.data);
document.getElementById("showMsg").innerText=response.data;
});
});
document.getElementById("test02").addEventListener('click', function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {cmd: "GetSelectedText"}, function(response)
{
if(response.res)
alert(response.res);
});
});
});
background.js
//background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
if(request.greeting=="hello"){
sendResponse({data: "This is the message sent from the background."});
}
return true; //send a response asynchronously, this will keep the message channel open to the other end until sendResponse is called.
}
);
content.js
// content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.cmd=="GetSelectedText")
{
var selectedText=window.getSelection().toString().trim();
if(selectedText&&selectedText.length)
{
console.log(selectedText);
sendResponse({res: selectedText});
}
}
return true;
}};