-
Notifications
You must be signed in to change notification settings - Fork 1
/
popup.js
88 lines (81 loc) · 2.97 KB
/
popup.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
let search = document.getElementById('searchPage');
search.onclick = function(element) {
var text = document.getElementById('searchParam').value;
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.executeScript(tabs[0].id,
{ code: `var arr = [], links = document.links; for (var i = 0; i < links.length; i++){arr.push(links[i].href);} arr;` },
function (test){
arr = test[0];
var lastTag = document.getElementById('charCount');
let chars = lastTag.value;
console.log(chars);
for (var i = 0; i < arr.length; i++) {
(function(arr, i){
let xhr = new XMLHttpRequest();
xhr.open("GET", arr[i], true);
xhr.onload = function(e) {
let url = arr[i];
console.log
findMatches(xhr.responseText, url, text, lastTag, parseInt(chars));
};
xhr.onerror = function() {
console.error("Error occured with XMLHTTPRequest");
}
xhr.send();
})(arr, i);
}
})
})
};
function findMatches(content, url, searchTerm, lastTag, chars){
content = content.replace(/(<([^>]+)>)/ig,"");
var n = content.search(searchTerm);
var indices = getIndicesOf(searchTerm, content, false);
if (indices.length == 0) return;
// create base url
var div = document.createElement('div');
div.setAttribute('class', 'matched');
var a = document.createElement('a');
a.setAttribute('href', url);
a.innerHTML = url;
div.appendChild(a);
checkCloseIndices(indices, chars);
console.log(indices);
// Grab strings
for (n in indices) {
let para = document.createElement('p');
para.innerHTML = '\n' + content.substring(indices[n] - chars, indices[n] + chars) + '\n';
div.appendChild(para);
}
lastTag.parentNode.insertBefore(div, lastTag.nextSibling);
lastTag = div;
}
// combines indices if too close to eachother
function checkCloseIndices(indices, chars) {
var last_i = indices.length - 1;
var i = indices.length - 1;
while (i--) {
if (indices[last_i] - indices[i] < chars * 2) {
indices.splice(i, 1);
continue;
}
last_i = i;
}
}
// Thanks stack overflow!
function getIndicesOf(searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}