Chrome Extension that copies image URL on click

我怕爱的太早我们不能终老 提交于 2019-12-14 02:19:24

问题


I'm brand new to making Chrome Extensions and have done the simple tutorials, but I'm having trouble finding what I need. I want the extension to allow a user to chose an image on a webpage, and then copy the URL for that image into the extension. Can anyone help me out? I'm sure if I see an example I'd get a better grasp on how extensions can interact with a page.


回答1:


From what I understand of your question, I'd say you want to create a context menu item that shows up when you right-click an image. For example, in your background script, use:

chrome.contextMenus.create({
    title: "Use URL of image somehow",
    contexts:["image"],
    onclick: function(info) {
        handleImageURL(info.srcUrl);
    }
});

function handleImageURL(url) {
    // now do something with the URL string in the background page
}

This will add a context menu item that shows up on all pages, but only when you right-click on images. When the user selects it, the onclick handler of the menu item fires handleImageURL with the URL of the image as the argument. The URL can be processed in any way you like, e.g., saved in a localStorage list, sent to a server via Ajax, or passed in a message to a listening content script in the current tab.

EDIT with alternative:

You might want a content script that gets injected into every page. The script could bind an event listener to every image element at load time:

// in my_content_script.js...
var imgs = document.getElementsByTagName("img");
for(var i = 0, i < imgs.length; ++i) {
    imgs[i].addEventListener("click", function() {
        alert(this.src);
        // do things with the image URL, this.src
    });
}

To inject it into all subdomains of example.com, your manifest would include:

...
"content_scripts": {
    "matches":["*://*.example.com/*"],
    "scripts":["my_content_script.js"]
},
...

Note that this pure-JS solution doesn't attach listeners to images dynamically added after load time. To do that in your content script with jQuery, use:

$(document).on("click", " img", function() {
    alert(this.src);
});

And add your jQuery file name to the scripts array in your manifest, next to my_content_script.js.




回答2:


Based on this Google Chrome Extension sample:

var images = [].slice.apply(document.getElementsByTagName('img'));
var imageURLs = images.map(function(image) {
  return image.src;
});
chrome.extension.sendRequest(images);

For a more detailed example (e.g. how to handle the request), you can check out this extension I wrote called Image Downloader



来源:https://stackoverflow.com/questions/10423670/chrome-extension-that-copies-image-url-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!