I'm working on a chrome extension and I'm trying to detect the input value in the popup.js file like this:
// popup.js
// Set up a listener for when the popup is opened
document.addEventListener("DOMContentLoaded", function () {
// Get a reference to the input field
var inputField = document.getElementById("input-field");
// Set up a listener for when the user types in the input field
// send a message to the background script to check if it's working
chrome.runtime.sendMessage({
type: "getSuggestion",
prompt: inputField.value,
});
inputField.addEventListener("input", function () {
// Send a message to the content script to get a suggestion
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
console.log("inputField.value: ", inputField.value);
chrome.tabs.sendMessage(
tabs[0].id,
{
type: "getSuggestion",
prompt: inputField.value,
},
function (response) {
console.log("response: ", response);
}
);
});
});
});
and I'm trying to send it to the background.js just to console log it for the moment like this:
// Set up a listener for messages from the content script
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.type === "getSuggestion") {
console.log("request.prompt: ", request);
return request.prompt;
});
And this is the content.js script:
// Listen for messages from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// Get the suggested text from the message
const suggestion = request.textSuggestion;
// Modify the DOM to display the suggested text to the user
const suggestionEl = document.createElement("div");
suggestionEl.innerHTML = suggestion;
suggestionEl.style.position = "absolute";
suggestionEl.style.top = "0";
suggestionEl.style.left = "0";
suggestionEl.style.backgroundColor = "white";
suggestionEl.style.padding = "10px";
suggestionEl.style.zIndex = "9999";
suggestionEl.style.fontSize = "16px";
document.body.appendChild(suggestionEl);
But I'm getting this error: popup.html:1 Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
here is the popup.html file just in case:
<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
<title>WordCompleter</title>
<link rel="stylesheet" type="text/css" href="popup.css" />
</head>
<body>
<div id="input-container">
<input type="text" id="input-field" />
</div>
<div id="suggestion-container">
<p id="suggestion-field"></p>
</div>
<script src="popup.js"></script>
</body>
</html>