您的位置:首页 > 其它

动手写一个简易的文档下载Chrome插件

2017-05-18 22:01 525 查看
参考官网:https://developer.chrome.com/extensions/getstarted

要做的事情:获取当前页面所有文档的下载链接,并生成列表提供下载功能。

实现的思路:获取所有
hre
属性值后缀为指定文档格式的
a
标签,并保存结果,弹出框提供文档格式筛选及下载功能。

插件使用Angularjs及Bootstrap框架。

popup.html

<body ng-controller="ctrl">
<div id="status"></div>
<div id="filter">
<label class="checkbox-inline">
<input ng-change="checkBoxChange()" name="docType" type="checkbox" id="inlineCheckbox1" ng-value="pdf"  ng-model="selectedType.pdf">pdf
</label>
<label class="checkbox-inline">
<input ng-change="checkBoxChange()" name="docType" type="checkbox" id="inlineCheckbox2" ng-value="docx"  ng-model="selectedType.docx">docx
</label>
<label class="checkbox-inline">
<input ng-change="checkBoxChange()" name="docType" type="checkbox" id="inlineCheckbox3" ng-value="ppt"  ng-model="selectedType.ppt">ppt
</label>
</div>
<div id="result">
<div ng-repeat="item in results track by $index" ng-show="selectedType[item.type]">
{{item.text}}  
<a ng-href="{{item.url}}" target="_blank">Download</a>
</div>
<div ng-if = "results.length == 0">
<i>Not Found</i>
</div>
</div>

</body>


popup.js

angular.module("app", [])
.controller("ctrl", function ($scope) {
$scope.selectedType = { "ppt": true, "docx": true, "pdf": true };
function isSelectedType(type) {
return $scope.selectedType[type];
}
$scope.checkBoxChange = function () {
var res = allResults.filter(function (data, index) {
return $scope.selectedType[data.type];
})
$scope.results = res;
$scope.$apply();
}
var allResults;
chrome.tabs.query({
active: true
}, function (tabs) {
var tab = tabs[0];
tab_title = tab.title;
chrome.tabs.executeScript(tab.id, {
file: 'dom.js'
}, function () {
chrome.tabs.sendRequest(tab.id, { type: "pdf, ppt" }, function (results) {
allResults = results;

$scope.results = results;
$scope.$apply();

});
});
});
})


dom.js

function getLinks(r, s) {
var links = document.querySelectorAll("a");
var results = [];
var seenLinks = {};

for (var i = 0; i < links.length; i++) {

if (links[i].href.indexOf(".pdf") !== -1 || links[i].href.indexOf(".docx") !== -1 || links[i].href.indexOf(".ppt") !== -1) {
var type = "";
if (links[i].href.indexOf(".pdf") !== -1) {
type = "pdf";
} else if (links[i].href.indexOf(".docx") !== -1) {
type = "docx";
} else if (links[i].href.indexOf(".ppt") !== -1) {
type = "ppt";
}
var obj = {};
obj.url = links[i].href;
obj.type = type;
obj.text = links[i].innerHTML;

results.push(obj);
}

}
return results;
};

chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {

sendResponse(getLinks(request, sender));
});


示例网页内容:

<a href="test1.pdf">test1.pdf</a>
<a href="test2.pdf">test2.pdf</a>
<a href="正则表达式30分钟入门教程.pdf">正则表达式30分钟入门教程.pdf</a>
<a href="test3.zip">test3.zip</a>
<a href="test3.docx">test3.docx</a>
<a href="test3.ppt">test3.ppt</a>
<a href="test3.text">test3.text</a>


效果:



项目地址:https://github.com/YiNanKai/chrome-extension-download-helper
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: