2

I'm writing an extension that reacts to right-clicks on images on the page. I'd like to know the image's dimensions to do further processing.

Out of the box, my callback gets a reference to the tab and an "info" object (OnClickData), which only exposes minimal information.

Has anyone hit this scenario before? I'm thinking of either

  • loading the image again based on the srcUrl (may not be reproducible if the URL is dynamic) and interrogating it
  • trying to walk the DOM of the tab to find the image and interrogate it (not sure if this would require a content script to cross the boundary from extension to webpage)
cldellow
  • 359
  • 6
  • 14
  • I might use http://stackoverflow.com/a/626505/689161; there shouldn't be much overhead anyway as the image should be cached. – gengkev May 29 '12 at 05:04
  • Since there already are similar extensions, you can simply investigate their code:https://chrome.google.com/webstore/detail/khagclindddokccfbmfmckaflngbmpon – Konrad Dzwinel May 29 '12 at 13:54

1 Answers1

2

What the Image Properties Context Menu extension does is to use a user script in combination with the context menu API.

The user script is injected into all pages, listens for context menu events, and sends the information about the image to the extension via chrome.extension.sendRequest:

document.addEventListener("contextmenu", function (e) {
    var elem = e.srcElement;
    if (elem instanceof HTMLImageElement) {
        var img = {
            src: elem.src,
            alt: elem.alt,
            height: elem.height,
            width: elem.width
        }
        chrome.extension.sendRequest(img);
    }
}, true);

The background page uses chrome.extension.onRequest.addListener to receive this data, and stores it in a global variable. The context menu API click callback reads data from this global variable.

That assumes that the chrome.extension.sendRequest call is always handled before the click callback, which may not always be the case. You may want to make the callback check if the data has arrived, and if not, try again a little while later (by using setTimeout).

Mihai Parparita
  • 4,236
  • 1
  • 23
  • 30
  • Thanks; based on my research, this seems like the most correct way of doing it. It's also pretty heavy weight, though, so I ended up going the route @gengkev suggested, which happens to work for my use cases. – cldellow May 29 '12 at 15:56