SendMessage from popup to content.js not working in chrome extension
I am trying to create a popup interface for a chrome extension. I cannot post from popup.html / popup.js to content.js script. Here's what I have so far. When I click on the extension icon, I get the clicked button. I click on it and nothing happens, no errors in the chrome javascript console and no message for content.js.
manifesto
{
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"manifest_version": 2,
"name": "extensiontest",
"version": "0.2",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"browser_action": {
"default_icon": "Beaker.png",
"default_popup":"popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs"
]
}
popup.html
<html>
<head></head>
<script src="popup.js"></script>
<body>
<input id="button1" type=button value=clickme>
</body></html>
popup.js
function popup(){
alert(1);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
});
button1=document.getElementById("button1");
button1.addEventListener('click', popup)
}
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
start();
}
}
);
function start(){
alert("started");
}
+3
source to share
1 answer
I changed yours popup.js
and used DOMContentLoaded
as a Chrome extension, for example:
popup.js:
function popup() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
});
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("button1").addEventListener("click", popup);
});
content.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
start();
}
}
);
function start(){
alert("started");
}
popup.html:
<!DOCTYPE html>
<html>
<head></head>
<script src="popup.js"></script>
<body>
<input id="button1" type=button value=clickme>
</body></html>
I tested on my end, it works.
+7
source to share