Search code examples
javascriptgoogle-chrome-extensiondom-events

How to know what you are right clicking on for a google-chrome-extension


I am trying to write a Google Chrome extension to basically favorite pictures. So you see a picture on a page that you want to remember but don't want to manually save it or save the image URL. You will be able to right click on the image and add it to your image favorites with this extension.

I have everything figured out except for when the user right clicks on the picture, I can't figure out how to get the image URL from that action. The solution would need to work on any normal page on the internet. I am not sure if I need a normal listener or what.


Solution

  • Your context menu item's onclick handler should expect an onClickData object as its first argument. This object will contain a srcUrl property, which is the src property of the image that was right-clicked.

    You'd set up your menu item like this:

    chrome.contextMenus.create({
        title: "Remember image as favorite",
        contexts: ["image"],
        onclick: function(data) {
            console.log("we're about to save " + data.srcUrl);
            // do whatever you need with data.srcUrl to save it
        }
    });