Chrome Extension Manifest 3 GIF not showing

  Kiến thức lập trình

I am developing an extension for Google Chrome that is supposed to show a GIF in overlay at the end of a timer.

The timer works just fine, but the image doesn’t get shown.

background.js

let timerId = null;

// Function to start the timer
function startTimer(duration) {
  // Clear existing timer
  if (timerId) {
    clearTimeout(timerId);
  }

  // Set new timer
  timerId = setTimeout(function() {
    // Inject content script into the active tab
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
      const activeTab = tabs[0];
      const tabId = activeTab.id; // Get the ID of the active tab
      chrome.scripting.executeScript({
        target: { tabId: tabId, allFrames: true }, // Use the tabId obtained above
        files: ['contentScript.js'],
      });
    });

    console.log("Timer ended");
  }, duration * 1000); // Convert seconds to milliseconds
}

// Listen for messages from the popup script
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if (message.action === 'startTimer') {
    const duration = message.duration;
    console.log("Received duration:", duration);
    startTimer(duration); // Start the timer
  }
});

contentScript.js

// Create a semi-transparent overlay
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'; // Semi-transparent black
overlay.style.zIndex = '9999'; 
document.body.appendChild(overlay);

// Create an image element
const imgSrc = 'AAA.gif'; 
const img = document.createElement('img');
img.src = imgSrc;
img.style.position = 'fixed';
img.style.top = '50%';
img.style.left = '50%';
img.style.transform = 'translate(-50%, -50%)';
img.style.zIndex = '10000';
document.body.appendChild(img);


setTimeout(function() {
  overlay.remove();
  img.remove();
}, 2000); 

I tried changing the approach and, if I create another tab after the timer, the GIF it’s shown accordingly. But I need it to work as above, instead of creating another tab.

I tried creating a notification after the timer, but the notification doesn’t get created.

New contributor

Valentina L is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT