Kei*_*ith 2 google-chrome-extension
我是制作Chrome扩展程序的新手,并完成了简单的教程,但我无法找到我需要的内容.我希望扩展程序允许用户在网页上选择图像,然后将该图像的URL复制到扩展名中.谁能帮我吗?我敢肯定,如果我看到一个例子,我会更好地了解扩展如何与页面交互.
根据我对您的问题的理解,我想说您要创建一个上下文菜单项,当您右键单击图像时会显示该项.例如,在后台脚本中,使用:
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
}
Run Code Online (Sandbox Code Playgroud)
这将添加一个显示在所有页面上的上下文菜单项,但只有在右键单击图像时才会显示.当用户选择它时,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
});
}
Run Code Online (Sandbox Code Playgroud)
要将其注入所有子域example.com,您的清单将包括:
...
"content_scripts": {
"matches":["*://*.example.com/*"],
"scripts":["my_content_script.js"]
},
...
Run Code Online (Sandbox Code Playgroud)
请注意,此纯JS解决方案不会将侦听器附加到加载时间后动态添加的图像.要使用jQuery在内容脚本中执行此操作,请使用:
$(document).on("click", " img", function() {
alert(this.src);
});
Run Code Online (Sandbox Code Playgroud)
并将您的jQuery文件名添加到scripts清单中的数组旁边my_content_script.js.
| 归档时间: |
|
| 查看次数: |
6591 次 |
| 最近记录: |