-
Notifications
You must be signed in to change notification settings - Fork 1
/
inject.js
69 lines (65 loc) · 2.36 KB
/
inject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
(() => {
const domain = location.protocol + '//' + location.host
const initAttr = ['data-src'] // 默认配置属性
let configAttr = ['data-src'] // 配置的属性
const getConfigAttrUrl = function() { // 获取所有配置属性的值
const attrUrl = []
if (configAttr.length > 0) {
configAttr.forEach((attr) => {
attrUrl.push(...getAllAttr(attr))
})
}
return attrUrl
}
const getAllAttr = function(attr) { // 获取对应属性的值
const attrs = []
const allDoms = document.querySelectorAll('[' + attr + ']')
allDoms.forEach((dom) => {
const attrValue = dom.getAttribute(attr)
attrs.push(concatUrl(attrValue, domain))
})
return attrs
}
const getBackgroundImage = function() { // 获取背景图片
const allDoms = document.querySelectorAll('*')
const allBgImageUrl = []
allDoms.forEach((element) => {
let url = window.getComputedStyle(element)['background-image'].match(/url\("(.+)"\)$/)
if (url && url[1]) {
allBgImageUrl.push(concatUrl(url[1], domain))
}
})
return allBgImageUrl
}
const getImgUrl = function() { // 获取所有图片的src值
const allImg = document.querySelectorAll('img')
const allImgUrl = []
allImg.forEach((img) => {
allImgUrl.push(concatUrl(img.src, domain))
})
return allImgUrl
}
// 接收popup的指令,如果action为all,则获取所有图片url,如果为attr,则获取属性图片
chrome.runtime.onMessage.addListener(({ action, attr }, sender, sendResponse) => {
if (attr) {
configAttr = []
configAttr.push(...initAttr)
configAttr.push(...attr.split(','))
} else {
configAttr = []
configAttr.push(...initAttr)
}
if (action === 'all') {
sendResponse({
attrImg: [...new Set(getConfigAttrUrl())],
bgImg: [...new Set(getBackgroundImage())],
img: [...new Set(getImgUrl())]
})
}
if (action === 'attr') {
sendResponse({
attrImg: [...new Set(getConfigAttrUrl())],
})
}
});
})();