Extension for Chrome: Implementing Various Content Scripts

I am looking to dynamically load different content scripts based on the currently selected page and tab. Currently, I have three content scripts at my disposal. My goal is to utilize two of them for one specific page and the third script for another page.

For Page 1:

content_script.js load_content_script.js

For Page 2:

newtab_content_script.js

As of now, my manifest appears as follows:

{
  "name": "Custom Plugin for AdData Express. Quickly generate Excel documents from selected brands.",
  "version": "1.0",
  "background_page": "background.html",
  "permissions": [
    "cookies",
    "tabs", 
    "http://*/*", "https://*", "*", "http://*/*", "https://*/*",
    "http://www.addataexpress.com", "http://www.addataexpress.com/*"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>", "http://*/*", "https://*/*"],
      "js": ["load_content_script.js", "content_script.js", "newtab_content_script.js", "jquery.min.js", "json.js"]
    }
  ],
  "browser_action": {
      "name": "AdData Express Plugin",
      "default_icon": "icon.png",
      "js": "jquery.min.js",
      "popup": "popup.html"
  }
}

What modifications should I make to the manifest or elsewhere to achieve this conditional loading of content scripts?

Answer №1

To make sure everything is covered, you would set up multiple matches sections within the "content_scripts" element in your manifest file:

"content_scripts": [
  {
    "matches": ["http://www.amazon.com/*"],
    "css": ["myamazonstyles.css"],
    "js": ["jquery.js", "myamazonscript.js"]
  },
  {
    "matches": ["http://www.ebay.com/*"],
    "css": ["myebaystyles.css"],
    "js": ["jquery.js", "myebayscript.js"]
  }
],

Answer №2

Instead of relying on content scripts defined by URL patterns in the manifest, it is recommended to utilize executeScript, allowing you to dynamically determine when to inject a JavaScript snippet or file:

// background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // consider other status stages for injection
  if (changeInfo.status === "complete") {
    const url = new URL(tab.url);
    if (url.hostname === "www.stackoverflow.com") {
    
      // script injection happens here
      chrome.tabs.executeScript(tabId, {file: "content_script.js"});
    }
  }
});

Ensure that you include the tabs permission in the manifest.json:

{
  // ...settings omitted...
  "permissions": [
    "tabs",  // don't forget this
  ]
}

Answer №3

It is recommended to utilize Programmatic Injection

chrome.tabs.executeScript(null, {file: "content_script.js"});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

utilizing JavaScript to play an audio file in .mp3 format on my timer

Hi everyone, I'm a complete beginner in JavaScript. Recently, I've been working on coding a timer that resets its countdown whenever there is mouse movement or a key on the keyboard is pressed. I've managed to get the timer functionality wor ...

GraphQL component properties

Working on a basic web application using React and GatsbyJS, with content management handled by NetlifyCMS. Utilizing gatsby-transformer-remark to load image paths for display through gatsby-transformer-sharp. Created an Image component that takes in the ...

I am currently encountering an issue with a code snippet that is not performing as anticipated and require clarification

import React, {useEffect, useState} from 'react'; export function App(props) { let [state, setState] = useState(2); console.log('outside', state); useEffect(()=>{ document.querySelector('.btn').addEventListener( ...

Issue: ray.intersectScene does not exist as a function

For my basic WebGL project, I have been utilizing the sim.js code and its components. Recently, when I attempted to use the frustum class (refer to this question), it required updating my three.js. Unfortunately, this caused an issue: TypeError: ray.inter ...

Do you always need to use $scope when defining a method in Angular?

Is it always necessary to set a method to the $scope in order for it to be visible or accessible in various parts of an application? For example, is it a good practice to use $scope when defining a method that may only be used within one controller? Consid ...

JQuery computes the grand total without displaying it on the screen

I have been working on creating a small e-commerce website, and recently integrated a jQuery program to calculate items in the shopping cart. I wanted to display the total amount of these items next to the cart, but despite seeing that the calculation was ...

Having trouble retrieving information using JSON from openweather.com

Currently, I am facing an issue while attempting to retrieve weather information from the openweather.com API using geo-location (latitude and longitude) data. Despite my efforts, I cannot seem to figure out why the data is not being retrieved successfully ...

Adding the node_modules directory to a global npm package: A step-by-step guide

I've developed an npm package with numerous dependencies. However, when I test my app using npm install -g ./, the application is added to the global npm directory without the node-modules folder. As a result, when the app is launched from the termina ...

Unusual AngularJS error encountered while performing calculations on object properties

After running a specific calculation in my code, I encountered an unexpected issue. if (typeof $scope.memoryTable[name][category]['total'] !== 'undefined') { $scope.memoryTable[name][category]['total'] = $scope.memoryTabl ...

Using TypeScript's union type to address compatibility issues

Below is a small example I've created to illustrate my problem: interface testType { id: number } let t: testType[] = [{ id: 1 }] t = t.map(item => ({ ...item, id: '123' })) Imagine that the testType interface is source ...

Utilizing React JS: Displaying or Concealing Specific Components Based on the URL Path

Is there a way to dynamically change the navbar items based on the URL without having separate navbar components for each side? My current navbar design features 3 links on the left side and 3 links on the right, but I want to display only one side at a ti ...

I am interested in setting up a flickr gallery where clicking on an image will display a pop-up showing the image along with its relevant tags, title, and photo ID

Page´s photo Hello there, I am currently working on creating a Flickr API using JavaScript and HTML. My goal is to search for photos and display them in an HTML page, but I'm struggling with implementing a pop-up feature that includes the photo' ...

Removing a user using Vue.js in combination with Firebase

Having trouble removing an account from Firebase in vue.js. Followed the firebase docs but it's not working as expected. Here is the button to delete: <template> [...] <div class="text-center"> <button type="button" class ...

Reducing ObjectId length in node.js with mongoose

Currently, my URLs have a lengthy structure like this: http://www.sitename.com/watch?companyId=507f1f77bcf86cd799439011&employeeId=507f191e810c19729de860ea&someOtherId=..... Due to the rapid growth in length, I am contemplating the idea of shorte ...

The functionality of Ajax loading content will fail when the link is already loaded

I am currently using an ajax script that dynamically replaces the content of #main with the contents of a loaded page based on the clicked link. For example, clicking on rddd would replace #main with the content of about.php. However, I encountered an is ...

The function HandleKeyPress is failing to recognize the input from the down arrow

I'm currently working on developing a customized and user-friendly select input using React.js. My goal is to have the functionality where the up and down arrow keys behave like the tab key within the context of selecting options. In order to achieve ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

What is the reason that the Mongoose updateMany() function only functions properly when combined with .then

Currently delving into the intricacies of Mongoose, I am perplexed as to why updateMany() requires a .then() at the end in order to be executed. For instance, here is the snippet that I'm endeavoring to execute, with the intention of altering the rat ...

JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next. I understand that I need some function ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...