Chr*_*ner -1 javascript google-chrome google-chrome-extension
我一直致力于创建我的第一个 chrome 扩展。我已经完成了几个可以在https://developer.chrome.com/extensions/getstarted上找到的示例扩展
如何制作一个扩展程序,以返回 Chrome 中打开的选项卡上所有图像的 url 列表?我已经问过这个问题,但我已经更新了我的问题,希望能让它更清楚。
我知道 javascript 的基础知识,所以我想用该语言创建扩展。这与另一个不同,因为我想获得完整的 url,我想使用简单的 javascript 而不是尝试使用我不知道的 json。
这是我的 manifest.json 文件
{
"name": "Getting Started",
"description": "Get The sources of the images",
"version": "2.0",
"permissions":[
"activeTab",
"tabs"
],
"browser_action":{
"default_title": "Image Source",
"default_popup": "popup.html"
},
"content_scripts":[
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)
这是我的 content.js 文件
var len = document.images.length;
var imgs = document.images;
var sources = "";
for (var i = 0; i < imgs.length; i++){
sources = sources + imgs[i].src + "<br>";
}
document.getElementById("sources").innerHTML = sources;
/*if (len > 0){
alert(len + " images were found on page");
}
else{
alert("No images were found on page");
}*/ // Used these to see if there were any images on the page
Run Code Online (Sandbox Code Playgroud)
最后是我的 popup.html
<html>
<head>
<title>Awesome extension</title>
<script src="content.js"></script>
</head>
<body>
<p id="sources">There might be images here</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您可以使用Array.prototype.map:
var imageUrls = Array.prototype.map.call(document.images, function (i) {
return i.src;
});
Run Code Online (Sandbox Code Playgroud)
这应该为您提供所有图像网址的数组。
编辑:
因此,要在单击扩展程序时从活动选项卡中获取图像,您可以使用chrome.tabs.executeScript而不是在 manifest.json 中包含 content_scripts 条目来注入内容脚本,并使用该Array.prototype.map函数获取图像源数组:
弹出窗口.html
<html>
<head>
<title>Awesome extension</title>
<script src="popup.js"></script>
</head>
<body>
<p id="sources">There might be images here</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
弹出窗口.js
var callback = function (results) {
// ToDo: Do something with the image urls (found in results[0])
document.body.innerHTML = '';
for (var i in results[0]) {
var img = document.createElement('img');
img.src = results[0][i];
document.body.appendChild(img);
}
};
chrome.tabs.query({ // Get active tab
active: true,
currentWindow: true
}, function (tabs) {
chrome.tabs.executeScript(tabs[0].id, {
code: 'Array.prototype.map.call(document.images, function (i) { return i.src; });'
}, callback);
});
Run Code Online (Sandbox Code Playgroud)
清单文件
{
"name": "Getting Started",
"description": "Get The sources of the images",
"version": "2.0",
"permissions":[
"activeTab",
"tabs"
],
"browser_action":{
"default_title": "Image Source",
"default_popup": "popup.html"
},
"manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3096 次 |
| 最近记录: |