【问题标题】:How to get a list of images urls in chrome extension如何在 chrome 扩展中获取图像 url 列表
【发布时间】:2017-05-14 06:24:15
【问题描述】:

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

找到

如何制作一个扩展程序,以返回 chrome 中打开的选项卡上所有图像的 src 列表?

我知道 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 
}

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

【问题讨论】:

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


【解决方案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);
});

ma​​nifest.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 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 2011-07-17
    • 2020-12-10
    相关资源
    最近更新 更多