0

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.

The developer tools show no errors as well.

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();

Ronika
  • 11
  • 2
  • Is your API on your localhost working? – WOWOW Aug 03 '23 at 07:32
  • does chrome have so called *developer* tools where any *errors* would be output? Also, your content script seems to be loaded for `` but I can guarantee not `` have an element with id;s `quote`, `member` and `when` – Jaromanda X Aug 03 '23 at 08:02
  • You cannot use AJAX in a content script in extension made for manifest version 3. You've used `fetch` in the injected **script.js**, you cannot do that. – Titus Aug 03 '23 at 08:08
  • @WOWOW Yes it's working – Ronika Aug 03 '23 at 17:46
  • @JaromandaX The developer tools didn't show any errors. Also, I have been using since using chrome://new-tab-page was giving error – Ronika Aug 03 '23 at 17:48
  • @Titus Thank you. What should I do instead? – Ronika Aug 03 '23 at 17:49

0 Answers0