1

How do I get the image alt tag of the selected image, is there a way around this ?

function addNewImageFromSelectionRightClickMenu() {
    chrome.contextMenus.removeAll(function() {
        chrome.contextMenus.create({
            title: "Add image to Product",
            contexts:["image"],  // ContextType
            onclick: newImageFromSelection // A callback function
        })
    });
}
function newImageFromSelection(e) {
    console.log(469, e);
    document
    injectedScriptDispatcher({
        action: "newImageInSelection",
        ...e
    });
}
Timofey Biryukov
  • 379
  • 3
  • 13
yungdenzel
  • 27
  • 6

1 Answers1

2

Solution 1.

The usual advice is to declare a content script that runs in all tabs and listens to contextmenu event, saves the clicked event target element, then processes it in onMessage listener (example).

However, such a content script will be needlessly running 99.99999999% of the time, it also requires broad host permissions which puts such an extension into the extremely slow manual review queue in Chrome Web Store and possibly other extension galleries.

Solution 2.

A possibly better approach is to use activeTab permission and a dynamically injected content script that retroactively gets the clicked element by looking for image src reported to the contextMenus callback.

manifest.json excerpt:

"permissions": ["activeTab", "contextMenus"],
"background": {
  "scripts": ["background.js"],
  "persistent": false
}

background.js:

chrome.contextMenus.onClicked.addListener((info, tab) => {
  chrome.tabs.executeScript(tab.id, {
    code: `(${findElement})(${JSON.stringify(info)})`,
    frameId: info.frameId,
    matchAboutBlank: true,
    runAt: 'document_start',
  }, ([result] = []) => {
    if (chrome.runtime.lastError) {
      console.error('Error: ' + chrome.runtime.lastError.message);
    } else {
      console.log('Alt:', result);
    }
  });
});
// this function's code will be executed as a content script in the web page
function findElement({mediaType, srcUrl}) {
  const tagName = mediaType === 'image' ? 'img' : mediaType;
  for (const el of document.querySelectorAll(tagName)) {
    if (el.src === srcUrl) {
      return el.alt;
    }
  }
}

This code doesn't try to pierce ShadowDOM which is an exercise for the reader (example in the wild). The shortcomings are a) the inability to pierce a closed ShadowDOM root and b) the possibility of a duplicate image with the same src but a different attribute that you want to retrieve (specifically, alt).

wOxxOm
  • 65,848
  • 11
  • 132
  • 136