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

To include a request parameter in every HTTP request made with $http in AngularJS

I am looking to utilize Angular's $http service to communicate with an API. However, I need to find a way to save my authorization token within $http so that it is included in every request, whether it is a post, get, put, or delete request. I have ob ...

Tips for creating a clickable textbox

Does anyone know how to make a textbox clickable even when it is set as readonly. I'm looking for a way to make my textboxes clickable like buttons because I have some future plans for them. <input type="text" readonly value="Click me" id="clickm ...

Using Google Chart API to create stacked bar charts with annotations using symbols

I am trying to annotate the bars in my stacked bar chart with currency symbols for profit and costs. While I have been able to successfully annotate the bars without currency symbols, I am facing difficulties in displaying them with the $ prefix. Can anyo ...

The functionality to deselect multiple options in a select box is not functioning properly

There seems to be an issue with removing the selected attribute from the selected values in a jQuery multiselect box. The console is not showing any errors. You can view a working example here The problem lies in this code snippet: $("#mltyslct option ...

How can I use AngularJS to initiate code to run after the view and controller have successfully synchronized a specific change?

I am currently using AJAX to load date ranges into a pair of SELECTs (managed with AngularJS ng-repeat), which are then transformed into a slider using jQuery UI's selectToUISlider. My concern is that selectToUISlider may behave unexpectedly if the SE ...

"Addclass() function successfully executing in the console, yet encountering issues within the script execution

I dynamically created a div and attempted to add the class 'expanded' using jQuery, but it's not working. Interestingly, when I try the same code in the console, it works perfectly. The code looks like this: appending element name var men ...

Unlocking the power of array destructuring in Nuxt's asyncData when working with Promise.all

Currently, I am delving into the world of Nuxt and Vue along with a MySQL database. These technologies are relatively new to me as I make the transition from WebMatrix. In my previous setup, I had a single Admin page that handled multiple tables with dro ...

Is it possible to dynamically create an interface using an enum in TypeScript through programmatically means?

Recently, I defined an enum as shown below: enum EventType { JOB, JOB_EXECUTION, JOB_GROUP } Now, I am in need of creating an interface structure like this: interface EventConfigurations { JOB: { Enabled?: boolean; }; JOB_EXECUTION: { ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

Working with repeated fields in Google protobuf in JavaScript

Consider this scenario: you have a google protobuf message called Customer with a repeated field as shown below. message Customer { repeated int32 items = 1; } What is the procedure for setting the repeated items field in javascript? ...

Issue with Pure Javascript FormData upload involving files and data not successfully processing on PHP end

My file upload form follows the standard structure: <form id="attachform" enctype="multipart/form-data" action="/app/upload.php" method="POST" target="attachments"> <!-- MAX_FILE_SIZE must precede the file input field --> <i ...

Implementing a PHP button update functionality sans utilizing an HTML form

I need a way to update my database with just a click of a button, without using any forms or POST requests. Most examples I've seen involve updating through forms and the $_POST method. Is there a simpler way to update the database by directly click ...

How can Next-auth handle redirection for 401 errors?

Currently, I am utilizing Next-auth in combination with rtk query. My goal is to configure the application so that whenever a request results in a 401 unauthorized error, the page will automatically redirect to the login page. How can this be achieved? I ...

What is the process for saving an SVG element from an HTML page as a downloadable text file?

I've been practicing creating SVG elements from scratch on an HTML page using Javascript. The texts within the SVG element are styled with typefaces fetched from the server through a "@font-face" declaration in the CSS file. It's been quite succe ...

Struggling to create an access token with the Slack API

My goal is to retrieve an access token from the Slack API. When I use the code provided below, it generates an authorization URL containing a temporary code in the query string. Once permissions are granted, the process redirects to /slack/oauthcallback. ...

Having trouble getting the node serialport module to function properly when using the child process fork()

My current project involves implementing an asynchronous read in USB using fork() from the child_process module in electron. Essentially, upon clicking a div (id="read"), a message is sent from the renderer process to the main process. The main process the ...

Issue: The system is unable to locate the module labeled './lib/binding/napi-v3/argon2.node'

After attempting to install bcrypt or argon2 with the command npm install --ignore-scripts --omit=dev, an error occurred: app-1 | node:internal/modules/cjs/loader:998 app-1 | throw err; app-1 | ^ app-1 | app-1 | Error: Cannot find modul ...

"Exploring the versatility of using variables in jquery's .css

I’m facing an issue where I need the rotation of a div to be based on the value stored in "anVar." This is what I currently have: function something() { $('.class').css('-webkit-transform:rotate('anVar'deg)') } The desi ...

A step-by-step guide on configuring data for aria's autocomplete feature

Currently, I am implementing aria autocomplete and facing an issue while trying to populate data from the server into the selection of aria autocomplete. I have tried setting the selected property of the aria autocomplete object, but it doesn't seem t ...

Looking to screen usernames that allow for the use of the DOT (.), underscore (_), and Dash (-)?

I am using jQuery to filter usernames that are exactly 3 characters long. The validation criteria includes only allowing the following special characters: ., _, and - var filter = /^[a-zA-Z0-9]+$/; Therefore: if (filter.test(currentval)) { //valid ...