Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract the innerHTML containing the email address and pass this information to the extension for searching purposes?

While I have successfully implemented the functionality for selected text on websites, the same does not apply when clicking on hyperlinked email addresses.

for(var i=0; i<numentries; i++)
{
//alert(_all[i][3]);
if(_all[i][3])
{
_all[i][0] = chrome.contextMenus.create({"title": _all[i][1], "contexts":["selection", "link"], "onclick": searchOnClick});
//alert("Menuitem created");
}
else _all[i][0] = -1;
}

var ask_options = getItem("_askoptions")=="true"? true : false;

if(ask_options){
//show separator
chrome.contextMenus.create({"type": "separator", "contexts":["selection", "link"]});
//show the item for linking to extension options
chrome.contextMenus.create({"title": "Options", "contexts":["selection", "link"], "onclick": function(){chrome.tabs.create({"url":"options.html"});}});
}
}

function searchOnClick(info, tab)
{
var itemindex = 0;
for(var i=0; i<numentries; i++)
{
if(info.menuItemId == _all[i][0])
{
//alert(i);
itemindex = i;
}
}
var ask_fg = getItem("_askbg")=="true"? false : true;
var ask_next = getItem("_asknext")=="true"? true : false;
var index = 1000;

var targetURL = _all[itemindex][2].replace("TESTSEARCH", info.selectionText);
targetURL = targetURL.replace("%s", info.selectionText);

Currently, the extension only searches for the selected text. When attempting to search for an email address hyperlink, it returns "undefined".

I need to modify this behavior so that instead of "undefined," the searched word is replaced by the actual email address in the hyperlink.

This is the desired outcome: https://i.stack.imgur.com/0OANN.png

Answer №1

Make sure to implement an event listener for the contextmenu.

To illustrate this, I put together a quick jsfiddle following Cat's example: https://jsfiddle.net/kds2Lze8/

The code snippet below attaches the event listener to the document and triggers upon right-click. By utilizing this event, you can extract the source element and its innerHTML content.

I trust you will find this information helpful!

document.addEventListener('contextmenu', function(event) {
    event.preventDefault();
    alert(event.srcElement.innerHTML);
    return false;
}, false);

Answer №2

When it comes to Chrome extension-specific features, your snippet is encountering an error that I couldn't troubleshoot without seeing your HTML markup. However, the script below should illustrate how to achieve your desired functionality.

Edit:
I initially overlooked your request to run the script on a right-click event. My apologies for that oversight. The updated version now addresses that requirement. It logs the innerHTML of the clicked element (excluding left-clicks) if the element is an anchor tag with an `href` attribute beginning with "mailto:".

// Execute the 'checkAnchorForEmail' function on non-primary click events
document.addEventListener("auxclick", checkAnchorForEmail);

function checkAnchorForEmail(event){
  let clickedElement = event.target;
  
  if(clickedElement.tagName.toLowerCase() === "a" && clickedElement.href){
    let comparedString = "mailto:";
    
    if(clickedElement.href.indexOf(comparedString) === 0){
      console.log(clickedElement.innerHTML);
    }
  }
}

// *Note: 'auxclick' triggers on any non-primary button click. To isolate right-clicks, consider using the 'contextmenu' event.

Additional Note:
To prevent the context menu from appearing before your script completes its tasks, you can utilize event.preventDefault();. In this case, you would need to manually display the menu later by firing the 'contextmenu' event on the target element.

If executing this action causes the script to loop indefinitely, you could try implementing conditional logic like the untested example below:

function checkAnchorForEmail(event){
    // Insert the code snippet here...
   
    if(event.target.dataset.ready != "true"){
        // event.preventDefault();
        // event.target.dataset.ready = "true";
        // Add necessary context menu modifications
    }
    else{
        // Context menu changes have already been applied, so display the menu here
    }
}

Referencing the MouseEvent interface mentioned in the code comments, you can follow this guide on triggering the context menu.

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

Ways to manage numerous AJAX actions within a single HTTP request?

Currently, I am utilizing jQuery to create a multipart web page containing a list of links that are updated through periodic AJAX HTTP requests. Each link on the page is triggered by a timer in JavaScript, causing it to make an HTTP request to its designat ...

Protractor's isDisplayed method may return a false value for an element that is actually visible

UPDATE #4: Eureka!! I made a breakthrough by recursively navigating through the parent nodes and returning the same values as shown below. Surprisingly, one of the parent nodes - the inner mat-drawer-container - also returned false for isDisplayed, while ...

An issue occurred during the project compilation using npm

My project installation process is giving me some trouble. Initially, when I run npm install, it successfully installs all the dependencies. However, when I proceed to execute npm run compile, I encounter an error. Below is the log file for a better under ...

Having trouble rendering the React app; encountered an error: JSX contents are unterminated

I am currently facing an issue while trying to fetch data from an API in React using Axios. How can I ensure that useEffect functions properly? My objective is to create a page by fetching data from an API in React through Axios. I have designed a compon ...

Is it possible for a Vue component to contain both data and props simultaneously?

How does a standard Vue component look? Vue.component('blog-post', { // camelCase in JavaScript props: ['postTitle'], template: '<h3>{{ postTitle }}</h3>' }) The basic documentation on components does not us ...

Create a visual representation of an image by sketching a detailed line profile using HTML5's

I am attempting to create an intensity profile for an image, using the x-axis as the line's length on the image and the y-axis as the intensity values along the length of the line. How can I achieve this on an HTML5 canvas? I have tried the code below ...

"Error: The property $notify is not found in the type" - Unable to utilize an npm package in Vue application

Currently integrating this npm package for notification functionalities in my Vue application. Despite following the setup instructions and adding necessary implementations in the main.ts, encountering an error message when attempting to utilize its featur ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

Having difficulty in closing Sticky Notes with JavaScript

Sticky Notes My fiddle code showcases a functionality where clicking on a comment will make a sticky note appear. However, there seems to be an issue with the Close Button click event not being fired when clicked on the right-hand side of the note. I have ...

Using Angular 2 for two-way binding with input masking

Encountering an issue with ng2 and inputmask. Here is the code snippet that's causing trouble: <div class="form-group col-sm-7"> <label class="control-label" for="sender-phone">Phone *</label> <input type="text" [(ngModel) ...

Double Assignment in JavaScript

Can you explain the concept of double assignment in ExpressJS and its functionality? An illustration is provided below using a code snippet from an ExpressJS instance. var server = module.exports = express() ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

I am looking for an image search API that supports JSONP so that users can easily search for images on my website

I am currently in the process of creating a blog platform. My goal is to allow users to input keywords on my site and search for images directly within the website. This way, I can easily retrieve the URL of the desired image. ...

Exploring the View-Model declaration in Knockout.js: Unveiling two distinct approaches

For my latest project, I am utilizing Knockout.js to create a dynamic client application with numerous knockout.js ViewModels. During development, I came across two distinct methods of creating these ViewModels. First method: function AppViewModel() { thi ...

Do we need to wait a considerable amount of time for an asynchronous function to run in a request?

I have a specific request that I need to address. The first snippet of code shows a function called handleUpdate1 which uses async/await to run a function named _asyncFuncWillRun10Minutes, causing the client to wait approximately 10 minutes for a response ...

The location.reload function keeps reloading repeatedly. It should only reload once when clicked

Is there a way to reload a specific div container without using ajax when the client requests it? I attempted to refresh the page with the following code: $('li.status-item a').click(function() { window.location.href=window.location.href; ...

What could be causing the issue with clicking on children of jstree not working?

I am encountering an issue with jstree. Once the data is changed, the click event does not work for every subsequent click. I find that I need to refresh the page in order to make it work. Here is a link to the jsfiddle: http://jsfiddle.net/2Jg3B/2121/ I ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

Unable to retrieve dynamically generated object property from an array in AngularJS 2+

Here is an example of an items array: this.itemList = [ { id: 1, name: 'a', address: 'as dasf a' }, { id: 2, name: 'b', address: 'as dasf a' }, { id: 3, name: 'c', address: 'as dasf a' } ]; ...

Backend data displayed on carousel presents either all images or none at all

I am currently working on a Django project that involves displaying a list of images in a Carousel format within my template. I have encountered an issue with setting the active class for the Carousel items. When I include the "carousel-inner active" clas ...