2016-12-29 54 views
1

我一直在创建我的第一个Chrome扩展。我做了几个可以在https://developer.chrome.com/extensions/getstarted如何获得铬扩展中的图像网址列表

找到样本扩展如何使一个扩展,将在镀铬返回一个打开的选项卡上的所有图像的src的名单?

我知道JavaScript的基础知识,所以我想用该语言创建扩展。这不像另一个,我想获得完整的网址,我想使用简单的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 
} 

,这里是我的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 

最后我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> 
+3

没有人会为你做这项工作。告诉我们你已经尝试过了。 – magreenberg

+1

我建议你阅读[Chrome扩展架构概述](https://developer.chrome.com/extensions/overview#arch)(也许通过阅读从那里链接的页面来工作)。它具有整体架构信息,可帮助您了解事物的组织/完成情况。 – Makyen

回答

1

去获取图片从活动选项卡中单击扩展名时,您可以使用chrome.tabs.executeScript注入内容脚本的具有在manifest.json一个content_scripts条目,并使用Array.prototype.map获得的图像源的阵列:

popup.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> 

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

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" 
    }, 
    "manifest_version": 2 
}