I am unable to make 2 way communication between content script and popup.
I could make a communication with content script and hence alert "Message received is showing up"
But feedback alert "response received" is not showing up. But the "response received" alert is showing when I inspect popup and then click on the button.
My question is that why would I need to inspect popup to get feedback alert "response received"? How can I get response without inspecting popup?
Popup HTML
<!doctype html>
<html>
<head>
<title>activity</title>
<script src="jquery.js"></script>
</head>
<body>
<button id="clickactivity">click</button>
<script src="popup.js"></script>
</body>
</html>
Manifest json
{
"manifest_version": 2,
"name": "Such Activity",
"description": "Wow",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://*/",
"<all_urls>"
],
"content_scripts": [
{
"matches": [ "https://*/*", "http://*/*" ],
"js": [ "jquery.js", "content_script.js" ]
}
]
}
Popup HTML
<!doctype html>
<html>
<head>
<title>activity</title>
<script src="jquery.js"></script>
</head>
<body>
<button id="clickactivity">click</button>
<script src="popup.js"></script>
</body>
</html>
Popup JS
function injectTheScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { sender: "Hi" }, function (response) {
if (response.receiver == "Hello") {
alert("Response recieved");
}
});
});
}
document.getElementById('clickactivity').addEventListener('click', injectTheScript);
Content script JS
$(document).ready(function () {
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.sender == "Hi") {
alert("Message Received");
sendResponse({ receiver: "Hello" });
}
});
});