如何获取Chrome扩展程序

时间:2016-12-29 22:18:43

标签: javascript google-chrome google-chrome-extension

我一直致力于创建我的第一个chrome扩展程序。我已经完成了几个可以在https://developer.chrome.com/extensions/getstarted

找到的示例扩展

如何制作一个扩展名,以便在Chrome中打开的标签页上返回所有图片的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>

1 个答案:

答案 0 :(得分:1)

要在单击扩展名时从活动选项卡中获取图像,您可以使用chrome.tabs.executeScript注入内容脚本,而不是在manifest.json中使用content_scripts条目,并使用Array.prototype.map来获取数组的图像&#39;来源:

<强> 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 
}