-
Notifications
You must be signed in to change notification settings - Fork 3
/
popup.js
85 lines (76 loc) · 3 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
// popup.js
document.addEventListener('DOMContentLoaded', () => {
const loader = document.getElementById('loader');
const status = document.getElementById('status');
const clearBtn = document.getElementById('clearData');
// Check for cached data when popup opens
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const formUrl = tabs[0].url;
chrome.storage.local.get([formUrl], (result) => {
if (result[formUrl]) {
displayResponse(result[formUrl], true); // true indicates cached data
clearBtn.style.display = 'block';
} else {
clearBtn.style.display = 'none';
}
});
});
document.getElementById('fetchData').addEventListener('click', () => {
loader.style.display = 'block';
status.textContent = "Fetching form data...";
// Clear existing storage before making new request
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const formUrl = tabs[0].url;
chrome.storage.local.remove([formUrl], () => {
// Execute content script to fetch fresh data
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
files: ['content.js']
});
});
});
});
// Clear button functionality
clearBtn.addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const formUrl = tabs[0].url;
chrome.storage.local.remove([formUrl], () => {
status.textContent = '';
clearBtn.style.display = 'none';
});
});
});
});
function displayResponse(data, isFromCache = false) {
const loader = document.getElementById('loader');
const status = document.getElementById('status');
const clearBtn = document.getElementById('clearData');
loader.style.display = 'none';
clearBtn.style.display = 'block';
const responseData = data.result;
if (Array.isArray(responseData)) {
status.innerHTML =
`<div class="response-header">
<h3>API Response ${isFromCache ? '<span class="cache-badge">(Cached)</span>' : ''}</h3>
</div>
<ul>` +
responseData.map((item, i) =>
`<li><strong>${i+1}. ${item.fullQuestion}:</strong>Ans. ${item.answer}</li>`
).join('') +
"</ul>";
} else {
status.textContent = "Unexpected response format from API.";
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "apiResponse") {
displayResponse(message.data, false); // false indicates fresh data
} else if (message.action === "apiResponseError") {
const loader = document.getElementById('loader');
const status = document.getElementById('status');
const clearBtn = document.getElementById('clearData');
loader.style.display = 'none';
clearBtn.style.display = 'none';
status.textContent = message.error;
}
});