-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
89 lines (80 loc) · 2.49 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
89
// Function to check if popup window exists
async function checkPopupStatus() {
try {
const windows = await chrome.windows.getAll({ populate: true });
const websiteUrl = await getWebsiteUrl();
const existingPopup = windows.find(window =>
window.type === 'popup' &&
window.tabs?.[0]?.url?.includes(websiteUrl)
);
if (existingPopup) {
const statusMessage = document.getElementById('status-message');
if (statusMessage) {
statusMessage.textContent = 'The pop-up is already open.';
}
return true;
}
return false;
} catch (error) {
console.error('Error checking popup status:', error);
return false;
}
}
// Function to get website URL from environment variables
async function getWebsiteUrl() {
try {
const result = await chrome.storage.local.get('envVariables');
return result.envVariables?.WEBSITE_URL || '';
} catch (error) {
console.error('Error getting website URL:', error);
return '';
}
}
// Function to open chat window
async function openChatWindow() {
try {
const isOpen = await checkPopupStatus();
if (!isOpen) {
const websiteUrl = await getWebsiteUrl();
if (!websiteUrl) {
throw new Error('Website URL not found in environment variables');
}
await chrome.windows.create({
url: websiteUrl,
type: 'popup',
width: 400,
height: 400,
left: 900,
top: 50
});
} else {
// Focus the existing window
const windows = await chrome.windows.getAll({ populate: true });
const websiteUrl = await getWebsiteUrl();
const existingPopup = windows.find(window =>
window.type === 'popup' &&
window.tabs?.[0]?.url?.includes(websiteUrl)
);
if (existingPopup) {
await chrome.windows.update(existingPopup.id, { focused: true });
}
}
} catch (error) {
console.error('Error opening chat window:', error);
const statusMessage = document.getElementById('status-message');
if (statusMessage) {
statusMessage.textContent = 'Error opening chat window. Please try again.';
}
}
}
// Initialize popup
document.addEventListener('DOMContentLoaded', () => {
const openChatButton = document.getElementById('openChatButton');
if (openChatButton) {
openChatButton.addEventListener('click', openChatWindow);
}
// Check initial popup status
checkPopupStatus().catch(error => {
console.error('Error during initialization:', error);
});
});