根据我对你的问题的理解,我想说你想创建一个上下文菜单 http://code.google.com/chrome/extensions/contextMenus.html右键单击图像时显示的项目。例如,在后台脚本中,使用:
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 发送到服务器,或者传递消息 http://code.google.com/chrome/extensions/messaging.html聆听内容脚本 http://code.google.com/chrome/extensions/content_scripts.html在当前选项卡中。
编辑替代方案:
你可能想要一个内容脚本 https://code.google.com/chrome/extensions/content_scripts.html被注入到每个页面中。该脚本可以在加载时将事件侦听器绑定到每个图像元素:
// 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
.