2016-12-29 57 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 
}