2

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

4

2 回答 2

6

根据我对您的问题的理解,我想说您想创建一个上下文菜单项,当您右键单击图像时会显示该菜单项。例如,在您的后台脚本中,使用:

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菜单项的处理程序handleImageURL以图像的 URL 作为参数触发。可以以任何您喜欢的方式处理 URL,例如,保存在localStorage列表中,通过 Ajax 发送到服务器,或将消息传递到当前选项卡中的侦听内容脚本

编辑与替代:

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

// 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,您的清单将包括:

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

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

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

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

于 2012-05-03T04:50:57.940 回答
0

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

于 2012-07-13T17:15:12.433 回答