Chrome扩展程序,可在点击时复制图片网址 [英] Chrome Extension that copies image URL on click

查看:178
本文介绍了Chrome扩展程序,可在点击时复制图片网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是制作Chrome扩展程序的新手,并且已经完成了简单的教程,但是我在寻找所需内容时遇到了麻烦.我希望扩展程序允许用户选择网页上的图像,然后将该图像的URL复制到扩展程序中.谁能帮我吗?我敢肯定,如果我看到一个示例,我会更好地了解扩展如何与页面交互.

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.

推荐答案

根据我对您的问题的理解,我想说您想创建一个

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
}

这将添加一个上下文菜单项,该菜单项显示在所有页面上,但仅当您右键单击图像时才显示.当用户选择它时,菜单项的onclick处理程序将以图像的URL作为参数触发handleImageURL.该URL可以用任何您喜欢的方式进行处理,例如保存在localStorage列表中,通过Ajax发送到服务器或内容脚本在当前标签中.

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.

编辑,另选:

您可能希望将内容脚本注入每个页面.该脚本可以在加载时将事件侦听器绑定到每个图像元素:

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
    });
}

要将其注入到example.com的所有子域中,您的清单应包括:

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

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

请注意,此纯JS解决方案不会将侦听器附加到加载时间之后动态添加的图像.要使用jQuery在内容脚本中执行此操作,请使用:

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);
});

并将您的jQuery文件名添加到清单中my_content_script.js旁边的scripts数组中.

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

这篇关于Chrome扩展程序,可在点击时复制图片网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆