I’m trying to make a chrome extension that loads dynamic quotes whenever a new tab is opened in chrome. However, it is not working.
I’ve tried to verify if everything is okay but nothing seems to work.
Can someone help me identify what the problem is and what I should do?
These are my codes.
background.js
chrome.runtime.onInstalled.addListener(() => {
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['script.js'],
});
});
console.log("service worker is working. ")
manifest.json
{
"manifest_version": 3,
"name": "BTS Comforting Quotes",
"version": "1.0",
"description": "Displays a random BTS comforting quote on each new tab.",
"host_permissions": [
"http://localhost:3000/random-quote/*"
],
"icons": {
"48": "icon48.png"
},
"background": {
"service_worker": "background.js"
},
"permissions": ["declarativeContent", "tabs", "scripting"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["script.js"]
}
]
}
script.js
// Fetch a random quote from the API and display it on the new tab page
function fetchRandomQuote() {
fetch('http://localhost:3000/random-quote')
.then(response => response.json())
.then(data => {
const quoteElement = document.getElementById('quote');
const memberElement = document.getElementById('member');
const whenElement = document.getElementById('when');
quoteElement.textContent = data.quote;
memberElement.textContent = `— ${data.member}`;
whenElement.textContent = data.when ? `(${data.when})` : '';
})
.catch(error => {
console.error('Error fetching random quote:', error.message);
});
}
// Execute fetchRandomQuote() when the content script is injected (on the new tab page)
fetchRandomQuote();