Unlocking the Potential of Google Chrome Extensions: Maximizing Functionality with Context Menus

Let's take a look at an example of something I want to accomplish, which I have simplified for posting purposes. My goal is to add multiple context menu items that trigger the same function. Within this function, I want to be able to differentiate which item was clicked and respond accordingly.

In this particular example, I am adding two context menu items: one for shortening a link with bit.ly and another for using tinyURL.

chrome.contextMenus.create({'title': 'Shorten with bit.ly',
                            'contexts': ['all'],
                            'onclick': shortenLink});

chrome.contextMenus.create({'title': 'Shorten with tinyURL',
                            'contexts': ['all'],
                            'onclick': shortenLink});

The function that receives the input looks like this. By default, both info and tab are passed along with the request, but distinguishing which context menu item triggered the function may not be straightforward.

function shortenLink(info, tab){

}

Below is a console dump displaying those two variables:

https://i.sstatic.net/X7H5Z.png

While setting up separate functions for each item is an option, I have numerous context menu items to add. Given that they share many similarities in code, my preference is to have a single "dispatch" function that all items utilize. Is there a way to achieve this?

Edit

Possibly, I can determine which menu item triggered the function by utilizing the menuItemId variable. Can I include additional information or data such as {method:'bitly'} when calling the function?

Answer №1

chrome.contextMenus.create({'title': 'Use bit.ly for URL shortening',
                            'contexts': ['all'],
                            'onclick': function(info, tab) {
                                shortenURL(info, tab, {option:'bitly'});
                            });

function shortenURL(info, tab, options){
    ...
}

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

Present information incrementally by showcasing each individual object element through knockout

I am looking to create a simple table layout that will allow me to showcase data from an array of objects one by one. By clicking on a button or a similar element, the next object in the array should be displayed. What makes this challenge interesting is ...

Sort through the JSON response data and swap out certain HTML tags

I need to pull information from a database and have it displayed in a div container with each piece of data on a separate line. Here is the data stored in the database: column name - prod_desc data - Camera :25MP | Memory :32GB | Battery: 3400mAh | Ram ...

I keep receiving a JavaScript alert message saying "undefined."

When I try to alert the item_id after giving input in the quantity textbox, I am receiving an undefined JavaScript alert. The code snippet below is not displaying the alert as expected: var item_id=$("#item_"+i).val();alert(item_id); In addition, my mode ...

Loop through a complex JSON object in Angular using ng-repeat

When working with a specific controller, I receive a JSON object that is quite intricate: { "184": { "title": "THE STONE ROSES", "sessions": { "1443564000000": { "num": 5 }, "1442959200000": { "num": ...

Tips for maximizing the efficiency of html script templates

I needed to automatically generate li elements, and initially I did so using a function within a loop that returned the text: function getLi(data) { return '<li>' + data + '</li>'; } Then I discovered a more efficient m ...

Learn how to effectively utilize DataBinder.Eval of repeater in ASP.NET button's OnClientClick JavaScript function

I am facing an issue with my asp.net webform repeater. Within the "ItemTemplate" of the repeater, I have added an asp:button and implemented the following code in the "OnClientClick" event of the button. // Here is a JavaScript function function Confirm ...

What is the best way to refresh a page using Vue 3 Composition API and router?

Once confirmed in Vue 3 Composition API router.push('/IssueList'); When arriving at the IssueList page, I want my issue-incoming and issue-send components to refresh. Although I am redirecting to the page, the IssueList page does not refresh. ...

Just running JavaScript code repeatedly in a loop

After running this script, I observed that there are 20 repetitions of the <button> tags. <?php for ($i = 1; $i <= 20; $i++) { ?> <button id="btn-<?php echo $i;?>">Button<?php echo $i;?></button> <script t ...

What are the steps to designing customizable drop-down content menus on websites?

I am looking to implement a feature where I can create content drop-down bars similar to the ones shown in the images. When a user clicks on the bar, the content should be displayed, and if clicked again, the drop-down should hide. I have searched for a so ...

Avoiding errors on the client side due to undefined levels in a specific response JSON can be achieved using the RESTful API

Below is a straightforward JSON response example: { "blog": { "title": "Blog", "paragraphs": [{ "title": "paragraph1", "content": "content1" }, { "title": "paragraph2", "content": "content2" }, { ...

Unable to complete CORS request in Safari following a 302 redirect

Encountering an issue with how Safari handles CORS requests. Here's the scenario: DomainA hosts a page that sends a XHR request to DomainB (origin header set to DomainA) DomainB responds with a 302 redirect to DomainC (origin header set to null, com ...

Obtain the date in the following format: 2016-01-01T00:00:00.000-00:00

Can someone help me convert this date to the correct format for the mercadolibre api? I need it to be like this: 2016-01-01T00:00:00.000-00:00 However, when I try with the following code: var date_from = new Date(); date_from.setDate(date_from.getDa ...

React-Native Error: Invalid element type detected

While attempting to run my React Native app on my iPhone using Expo, I encountered an error displayed in a red background area. Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

"Discover the best way to sort through an array of complex objects with varying levels of nesting using a specified search

I have come across similar answers, but none of them go beyond two levels deep. Therefore, I believe this is not a duplicate problem. My task is to filter an array of objects where each object may contain nested objects of unknown depth. In my data structu ...

Updating front end data using Node.js - A Comprehensive Guide

I am looking to create a website using node.js that can dynamically display a plot and update the data every minute without needing to refresh the entire page. As someone new to node.js, I am interested in learning how to use "get" requests to update the d ...

Transforming Objects with THREE.js: Navigating the Order of Transformations

Currently learning THREE.js and facing a bit of a newbie issue. I have a JSON object with dynamic updates, containing data for 4 walls. The JSON structure is as follows: { ... walls: [{ start: { x : 0, y : ...

Transmit analytical data to an external domain without expecting a reply

Initial Conditions I have ownership of mysite.com I lack ownership of othersite.com, but I am able to embed javascript code on that site Query What is the method to transmit analytic data from othersite.com to mysite.com ? ...

Issue with callback and logic in Angular 2.0 form handling

As a beginner in Angular, I am attempting to develop a simple script that updates the price when the value of a form input changes. There are various methods for utilizing Angular with class-driven and directive-driven models. Despite reading the documenta ...

Encountering module resolution issue following npm-link for the shared component repository

Attempting npm-link for the first time to establish a shared component repository, and encountering an issue. The project seems to be linked correctly based on this message: /Users/tom.allen/Development/main/project/node_modules/@linked/project -> /usr ...

MUI Alert: Encountered an Uncaught TypeError - Unable to access properties of undefined when trying to read 'light' value

After utilizing MUI to create a login form, I am now implementing a feature to notify the user in case of unsuccessful login using a MUI Alert component. import Alert from '@mui/material/Alert'; The code snippet is as follows: <CssVarsProvide ...