I am creating a Chrome extension and try to fetch data from a server inside of addEventListener
when a button is clicked. I get an error Uncaught (in promise) TypeError: Failed to fetch at request
. I tried to run the request in a separate file with node file.js
and it worked. I thought that I eventually need to add a permission inside of manifest.json
for fetching data from a server but I cannot find any ressources for that. How can I fetch data from a server in a Chrome extension?
content.js
document.addEventListener("click", (event) => {
if (event.target.innerText == "Reply") {
console.log("reply clicked");
function request(email) {
let _data = {
prompt: email,
}
fetch('fetch_address', {
method: "POST",
body: JSON.stringify(_data),
headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json())
.then(json => console.log(json['response']));
}
request('this is a test message to check the API');
}
});
background.js
console.log("background.js loaded");
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log("message received in background.js");
if (request.type == "click_event") {
console.log("click event captured in current webpage");
}
});