Is it possible to use tabs.create to generate a tab and then inject a content script, where the code attribute is effective but the file attribute seems to be ineffective

I am currently facing an issue with injecting a content script file into a newly created tab. The problem lies in the fact that I keep receiving an error stating

chrome.tabs.executeScript(...) is undefined
in the console output of the Popup. It may be worth mentioning that Vue is being used in this project. Let me provide you with some code snippets.

Let's start with the manifest:

{
  "manifest_version": 2,
  "name": "Example",
  "description": "Performs common searches based on input",
  "default_locale": "en",
  "permissions": [
    "<all_urls>",
    "tabs"
  ],
  "background": {
    "scripts": [
      "js/background.js"
    ]
  },
  "browser_action": {
    "default_popup": "popup.html",
    "default_title": "Example",
  }
}

Moving on to the code within the popup Vue component's "method" attribute:

search: function() {
  const urls = Object.values(this.$store.state.urls);
  urls.forEach((item, index) => {
    chrome.tabs.create({ url: item }, (tab) => {
        // Works!
        chrome.tabs.executeScript(tab.id, { code: "console.log('Injected JS')" });
        // Doesn't work..
        chrome.tabs.executeScript(tab.id, { file: "/content-script.js" });
        // Doesn't work..
        chrome.runtime.sendMessage({ message: "Popup", tabId: tab.id })
    });
  });
}

The content script looks like this:

(function() {
    console.log("Injected JS from file!");
})();

Lastly, background.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if(request.message === "Popup") {
        console.log("Got message from popupJS in background.");
        console.log("Tab id: " + request.tabId);
        chrome.tabs.executeScript(request.tabId, { file: "/content-script.js" });
    }
});

In the main code section, three different approaches were attempted:

  1. executeScript using the code option - successful.
  2. executeScript using the file option - unsuccessful.
  3. executeScript in the background script - also unsuccessful. This was expected to resolve the
    chrome.tabs.executeScript(...) is undefined
    error but unfortunately did not succeed even after printing the tab id.

Considering a possible pathing issue with content-script.js, I referred to both the Chrome docs and the more informative Mozilla docs:

To ensure cross-browser compatibility, you can specify the path as a relative URL starting at the extension's root, for example: "/path/to/script.js".

The content script is located at extension-project/content-script.js in the project root. Although attempts were made by incorporating the project folder in the path string to cover all bases, no progress has been achieved.

If you have any insights or suggestions on where I might be going wrong, they would be greatly appreciated.

Answer №1

When it comes to writing permissions in the manifest.json file, it's important to do it correctly. Here is an example of how it should be done:

  "permissions": [
    "scripting"
  ]

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

Trouble with the datepicker

I tried using the datepicker from and followed its demo, but unfortunately, the datepicker is not showing up on my page. I have gone through everything carefully, but I am unable to identify the reason behind this issue. Could someone please assist me i ...

Using AngularJS: The ultimate guide to invoking a service within a module

I have a controller that successfully calls a service. However, I now need to access a method within that service from another module. How can I achieve this? BaSiderbarService: (function() { 'use strict'; angular.module('BlurAdmi ...

Why is it that this JavaScript isn't working as intended in the popup form?

</br> s_foot"> * use ajax.jquery as control event. like $("#save").click(function(){.....}); <script type="text/javascript>" var wp; var position; var pid; var product_name; var production_date; In this script, I am attempting to re ...

Innovative Functions of HTML5 LocalStorage for JavaScript and TypeScript Operations

Step-by-Step Guide: Determine if your browser supports the use of localStorage Check if localStorage has any stored items Find out how much space is available in your localStorage Get the maximum storage capacity of localStorage View the amount of space ...

Is Axios phasing out support for simultaneous requests?

According to the current axios documentation, there is a section that is not very well formatted: Concurrency (Deprecated) It is advised to use Promise.all instead of the functions below. These are helper functions for managing concurrent requests. axio ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

Activate just the show more / show less button on the website that has several buttons with identical ids

Whenever the "show more" button is clicked, additional images are displayed in the gallery and the button text changes to "show less". However, in my ExpressionEngine (CMS) templates and entries, all "show more" buttons share the same id, causing other but ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...

What is the impact of a floated element on vertical spacing?

I have come across an article discussing the usage of CSS, but I am puzzled as to why image number four is not positioned below image number one. Instead, it appears below image number three. Can someone please explain this to me? Here is the HTML code sni ...

Experiencing disconnection from SQL server while utilizing the Express.js API

Im currently working on an API that retrieves data from one database and posts it to another database, both located on the same server. However, I am facing issues with the connections. Initially, everything works fine when I run the app for the first time ...

Retrieve the value of a dynamically added or removed input field in JQuery using Javascript

Check out this informative article here I'm looking for a way to gather the values from all the text boxes and store them in an array within my JavaScript form. I attempted to enclose it in a form, but I'm struggling to retrieve the HTML ID beca ...

What are the best practices for implementing image-slice in node.js?

I attempted to utilize image-slice to divide an image into multiple parts using Node.js. I tried installing npm i image-to-slices, sudo port install cairo, npm i canvas, and brew install pkg-config cairo pango libpng jpeg giflib. However, I still encounte ...

There was an issue with the JSON parsing process due to an unexpected token 'o' at position

Trying to extract titles from a JSON object for a specific feature, here's an example of the JSON structure: [ { "title": "Example 1", "url": "http:\/\/www.example1.com\/" }, { "title": "Example 2", "url": "http:& ...

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selectionChange($event){ let array ...

I need a layout similar to the navbar on http://thecoloradan.com/ but I am not asking for instructions on how to do it

Have you seen the stunning navbar on this website? It appears to merge with the background upon loading, then smoothly shifts to the top of the page as you scroll. The transition is accompanied by a lovely animation. I am curious about the steps needed to ...

Apply SetTimeout exclusively for desktop devices

A website I'm working on has a background video from YouTube using YTPlayer. To enhance the user experience, I have implemented a CSS spinner that displays while the page is loading. However, I noticed that the spinner disappears before the video fini ...

"Encountering issues with logging in through AngularJS and the $http request functionality

My goal is to login using $http and GET of REST web services. This is my approach: Retrieve data based on username and password using $http.get Store the result in $scope.getResult=res; Assign variables to the retrieved data: var result=$scope.getResult ...

Node.js program experiences issues with incorporating netCDF files

I am attempting to encode a NetCDF file within my Node.js program using the netcdf library, which can be found at https://www.npmjs.com/package/netcdf. After running the program, I encountered the following error: C:\app [master +2 ~1 -0 !]> npm ...

Exploring the React component life cycle: Understanding the distinction between render and return, and what happens post-return

This question pertains to the concepts surrounding react component life cycles. Below is an example code snippet provided as a general reference. const Modal = ({ className, variant, width, withCloseIcon, isOpen: propsIsOpen, onClose: tellParen ...

Issue with Material-ui IconButton's edge properties not functioning as expected

Is there a way to position the delete icon on the right side of the screen? It seems like using edge= "end" is not working as expected. If you'd like to take a look, here is the sandbox link: https://codesandbox.io/s/admiring-silence-vwfoe? ...