0

I am trying to create a chrome extension. One of the functionalities I want to implement is to redirect the user's browser to a randomly selected link from a list of matching links stored in the extension's synced storage. A user types in the name of a youtube and if the name matches a youtube channel all the links in the description section of the 5 latest released videos get fetched and the user can save them. Let's say there is a 'www.amazon.com/mrbeast' link saved. If the user tries to load amazon.com via the browser the users should get redirected through the 'www.amazon.com/mrbeast' link. Unfortunately my code does not work. The links get saved but for some reason my code in my background.js file does redirected the user.

My background.js file:

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'loading') {
    chrome.storage.sync.get(null, function(result) {
      console.log("Storage sync is working!!!")
      const links = Object.values(result).flat();
      const matchingLinks = links.filter(link => {
        if (tab.url.startsWith(link)) {
          console.log(`The match is: ${link}`);
          return true;
        } else {
          console.log('Sorry, no match found')
          return false;
        }
      });
      
      if (matchingLinks.length > 0) {
        console.log('2nd if statement');
        const randomMatchingLink = matchingLinks[Math.floor(Math.random() * matchingLinks.length)];
        const allMatchingLinks = links.filter(link => link === randomMatchingLink);
        const randomLink = allMatchingLinks[Math.floor(Math.random() * allMatchingLinks.length)];
        chrome.tabs.update(tabId, { url: randomLink });
        console.log('redirected my friend')
      }
    });
  }
});

My manifest file:

{
  "manifest_version": 3,
  "version": "0.1",
  "name": "Firebase Auth + MV3 Extension",
  "description": "Webpack Modular Framework!",
  "action": {
    "default_popup": "./popup.html",
    "default_icon": {
      "16": "./src/icons/get_started16.png",
      "32": "./src/icons/get_started32.png",
      "48": "./src/icons/get_started48.png",
      "128": "./src/icons/get_started128.png"
    },
    "default_title": "Getting Started Firebase + MV3!"
  },
  "permissions": [
    "storage",
    "activeTab",
    "scripting",
    "identity",
    "tabs"
  ],

"host_permissions":[
  "all_urls"
],

  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content.js"
      ]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },
  "icons": {
    "16": "./src/icons/get_started16.png",
    "32": "./src/icons/get_started32.png",
    "48": "./src/icons/get_started48.png",
    "128": "./src/icons/get_started128.png"
  },
  "options_page": "options.html",
  "oauth2": {
    "client_id": "679100910256-52b33aqmmjn8fmsp76qmt273j76vhcf4.apps.googleusercontent.com",
    "scopes": [
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/userinfo.profile"
    ]
  }
}

and for good measure the links.js file that fetches and saves the links:

const currentChannelName = localStorage.getItem('channelName');
console.log(currentChannelName);

document.addEventListener("DOMContentLoaded", function(event) {
  const heading = document.getElementById('aff_links');
  heading.innerText += ` for ${currentChannelName}`;
  console.log("javascript connected!")
  

});

const affiliateLinksUl = document.getElementById('affiliate-links');

// Get the video descriptions from the URL parameter and parse it back into an array
const urlParams = new URLSearchParams(window.location.search);
const videoDescriptions = JSON.parse(decodeURIComponent(urlParams.get('videoDescriptions')));

// Declare and initialize the storage variable
const storage = chrome.storage.sync;

// Loop through the video descriptions and create li elements with links
videoDescriptions.forEach(description => {
  const urlRegex = /(https?:\/\/[^\s]+)/g;
  const matches = description.description.match(urlRegex);
  if (matches) {
    matches.forEach(match => {
      const link = document.createElement('a');
      link.textContent = match;
      link.href = match;
      if (match.startsWith('http') || match.startsWith('https')) {
        const li = document.createElement('li');
        li.appendChild(link);
        affiliateLinksUl.appendChild(li);
        li.classList.add('style');
        link.addEventListener('click', function(event) {
          event.preventDefault();
          storage.get(currentChannelName, function(result) {
            const links = result[currentChannelName] || [];
            if (!links.includes(event.target.href)) {
              links.push(event.target.href);
              storage.set({ [currentChannelName]: links }, function() {
                console.log('Link saved to storage');
              });
            } else {
              console.log('Link already exists in storage');
            }
          });
        });
      }
    });
  }
});
enter code here
Julius
  • 1
  • 3
  • Debug it in [devtools of background.js](/a/10258029). Set a breakpoint inside the listener and step through the code, inspect the variables. – wOxxOm Apr 04 '23 at 19:51

0 Answers0