Extension for Chrome - Executing Javascript via Context Menu

I'm currently working on a project involving a Chrome Extension that aims to enable disabled drop-down menus. Strangely, when running the script in the Console, everything works flawlessly. However, when executing it through the extension, the functions are called but nothing happens.

Your assistance would be greatly appreciated.

manifest.json

{
 "name": "4x6 Mac Menu",
 "manifest_version": 2  
 "version": "0.1.4",
 "description": "Overrides Disabled Drop Down",
 "permissions": ["contextMenus"],
 "background": {
 "scripts": ["sample-click.js"]
 }
}

sample-click.js

function Enable46(info, tab) {
    console.log("Enable 4x6 was clicked.");

    var inputs = document.getElementsByClassName('psSelect');
    for(var i = 0; i < inputs.length; i++) {
        inputs[i].disabled = false;
    }

   console.log("Drop Enabled.");
}

chrome.contextMenus.create({
    title: "Enable 4x6",
    contexts: ["page"],
    onclick: Enable46,
});

Another attempt involved adding a listener as background. Although the console log is displayed, the event fails to carry out the intended function.

manifest.json

{
  "name": "4x6 Enable",
  "description": "Enable 4x6 Print Option on Mac",
  "version": "0.1",
  "manifest_version": 2,
  "permissions": [
    "contextMenus",
    "activeTab"
  ],
  "background": {
     "persistent": false,
    "scripts": ["bg.js"]
  }
}

bg.js

/* Create a context-menu */
chrome.contextMenus.create({
    id: "myContextMenu",   
    title: "4x6 Label",
    contexts: ["all"]
});

/* Register a listener for the `onClicked` event */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (tab) {
        /* Create the code to be injected */
        var code = [
        'var input = document.getElementsByClassName("psSelect");',
        'for(var i = 0; i < inputs.length; i++) { inputs[i].disabled = false; }'
         ].join("\n");

         console.log("Enable 4x6 was clicked.");

        /* Inject the code into the current tab */
        chrome.tabs.executeScript(tab.id, { code: code });
    }
});

Answer №1

This solution was successful! Interestingly, it had to be divided into 3 separate files.

setup.json

{
  "name": "Dropdown Activation",
  "description": "Activate Dropdown Menu",
  "version": "0.3",
  "manifest_version": 2,
  "permissions": [
    "contextMenus",
    "activeTab"
  ],

  "background": {
     "persistent": false,
    "scripts": ["bg.js"]
  }
}

bg.js

/* Setting up a context-menu */
chrome.contextMenus.create({
    id: "myContextMenu",   // <-- required for event-pages
    title: "Enable Dropdown",
    contexts: ["all"]
});

/* Adding an onClick listener */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (tab) {
        /* Inject the code into the current tab */
        /* chrome.tabs.executeScript(tab.id, { code: code }); */
        chrome.tabs.executeScript(tab.id, {file: "content_script.js"}); 
    }
});

content_script.js

var inputs = document.getElementsByClassName('psSelect');
    for(var i = 0; i < inputs.length; i++) {
   inputs[i].disabled = false;
}

document.getElementById("PrintLabelsPrinter").value = "1-1";

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

An efficient method for removing a column using JavaScript

Hello, I'm seeking assistance with the following code snippet: $(document).on('click', 'button[id=delete_column]', function () { if (col_number > 1) { $('#column' + col_number).remove(); $('#col ...

Display a still image in cases where the browser does not support 3D images

I need to display a 3D image in my HTML page if the browser supports canvas, otherwise I want to show a static image. The image should be loaded dynamically when the page loads. <!DOCTYPE html> <html class="no-js" lang="en"> <head> ...

Arrangement of images in an array

Here's the scenario I'm facing. https://i.stack.imgur.com/FbAfw.jpg So, I have an array of images that I want to use to create a gallery with a specific layout. I've tried using grid and playing around with :nth-child(even) and :nth-child( ...

Encountered a 404 error while handling the Express 4 module, indicating that the 'html' module could not be

I need to update my express app to handle 404 (and 500) errors by displaying HTML instead of plain text. I have been able to show text to the client for 404 errors, but now I want to show HTML instead. My 404.html file is located in the /app directory. Cu ...

Ensuring telephone numbers are properly validated using regular expressions

I have a regex for validating telephone numbers that is working for most cases except one. ^(\+?\ *[0-9]+)([0-9 ]*)([0-9 ])*$|(^ *$) The requirements are: 1. Allow only numeric values 2. Allow plus sign only at the beginning The ...

Transmit ByteArray to JavaScript

Is there a way to send a jpg image as a ByteArray from ActionScript 3 to JavaScript? Additionally, how can one convert a ByteArray back into an image using JavaScript? ...

Enhance data granularity in Jquery Flot by zooming in as the user interacts

I'm currently working on creating an interactive chart that allows users to zoom in for a more detailed view of the data. For instance, when viewing data over a default zoom period of 3 months, there would be one data point displayed every 24 hours. H ...

Encountering a StaleElementReferenceException when trying to navigate back in Selenium WebDriver

My current challenge involves crawling through anchors within a web page using Selenium WebDriver. One approach I have considered is gathering the anchors in a list, clicking on each one, and then navigating backwards after each click. Below is the code sn ...

Showing the initials of a user at the top of an SVG using ReactJS

https://i.sstatic.net/oJgXs.png I require the user's initials to be displayed on the avatars as a grey circle with those initials. I have the function ready, but I am unsure of how to implement it in the JSX code for the Dropdown menu (using Semantic ...

Is ReactJS known for its exceptional performance in rendering large matrices?

Although I have no prior experience with ReactJS, I've heard about a great feature it offers called virtual DOM. It reminds me of the concept of virtual elements in Silverlight where invisible elements are removed from the tree to enhance user-perceiv ...

The canvas grid is malfunctioning and failing to display correctly

My current code allows me to draw a grid on a canvas with multiple lines, but I'm encountering an issue when trying to render 25 or more lines - some of them don't appear on the canvas. This problem becomes more noticeable when there are 40 or mo ...

The incorrect value of variable V is being passed to the doSomethingWithData(v) function. This could lead to unexpected results

const Greetings = () => { const [num, setNum] = React.useState(1); React.useEffect(() => { setTimeout(async () => { await setNum(2); processData(num) }, 3000) }, []); retur ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...

Showing pictures from a JSON source

I am currently facing an issue while trying to display the cover art along with the search results. There seems to be a problem in the img src tag that is preventing the app from loading properly. Interestingly, when I direct the img to data.tracks[i].albu ...

Exploring content in Embed message fields

Can anyone help me with logging the contents of an embed received from a specific bot? I've tried some basic things but seem to be missing something. Please review my code and let me know what I'm doing wrong and how I can improve it. Thank you i ...

Display HTML code within a data attribute

I have a function that modifies an element from OpenLayers. In the official documentation, it mentions that the property label accepts either HTML or a string. methods: { onUpdatePosition (coordinate) { this.deviceCoordinate = coordinat ...

Substitute the comma with a space

Here is my input code snippet: (((text(text here))) AND (test3) Near (test4) NOT (test5) NOT (Test6)),((tttt,tttt)),((and,lol)),((hbhbhbhbhbh)) This is the output I get: (((text(text here))) AND (test3) Near (test4) NOT (test5) NOT (Test6) (tttt,tttt) (an ...

What steps do I need to take to create a customizable Angular Material NPM module?

Can a custom npm module be created using Angular Material that allows the components to be styled by the consuming app's unique theme? For instance, imagine an npm module with a component containing the following template: <button mat-raised-butt ...

What is the best way to create row numbers within a Vue component?

I am working on a project with two Vue components. The first component code looks like this: <template> <div> <b-row> <div class="pl-2 d-flex"> <div class="card-body"> <p cl ...

EffortlessDrop.js and anchors

Currently using EasyDropDown.js to style a select element, which creates a modern dropdown menu using jQuery. I'm curious if it's possible to include a hyperlink in one of the select options. Here's an example of what I'm trying to ach ...