-
Notifications
You must be signed in to change notification settings - Fork 7
/
backgroundScript.js
74 lines (67 loc) · 2.52 KB
/
backgroundScript.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
// Listener for when the Chrome extension is installed.
chrome.runtime.onInstalled.addListener(() => {
// Define the environment for the extension, either "prod" or "dev".
const environment = "prod";
// const environment = "dev";
// Set the website URL based on the environment.
const websiteUrl = (environment === "dev") ? "http://localhost:3000" : "https://vibinex.com";
// Store the website URL in Chrome's local storage.
chrome.storage.local.set({ websiteUrl }).then(_ => console.log(`Website URL set to ${websiteUrl};`))
.catch(error => console.error(`Failed to set website URL: ${error}`));
// Make an API call to the backend to create a Rudderstack event when the extension is installed.
chrome.storage.local.get(["userId"]).then(({ userId }) => {
const body = {
userId: userId || "anonymous-id", // Use the stored userId or "anonymous-id" if not available.
function: 'chrome-extension-installed'
};
const url = `${websiteUrl}/api/extension/events`;
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify(body)
})
.then((response) => response.json())
.then((data) => {
console.info(`[vibinex] Successfully sent installation event to backend. Response: ${JSON.stringify(data)}`);
}).catch(error => console.error(`[vibinex] Failed to send installation event to backend: ${error}`));;
});
});
/**
* Checks Logged in status for showing indicator on supported pages like github and bitbucket.
* @param {string} websiteUrl
* @param {string} provider
* @returns {Promise<boolean>}
*/
async function checkLoginStatus(websiteUrl, provider) {
let result = false;
try {
const res = await fetch(`${websiteUrl}/api/auth/session`, { cache: 'no-store' });
const json = await res.json();
if (json.user && json.user.auth_info && json.user.auth_info[provider]) {
result = true;
}
} catch (err) {
console.error(err);
}
return result;
}
/**
* Listener to handle login status check request.
* The api session request only works via extension background script due to the need of auth cookies in request.
*/
chrome.runtime.onMessage.addListener(
function (request, _, sendResponse) {
const message = JSON.parse(request.message);
if (message.action === "check_login_status") {
const websiteUrl = message.websiteUrl;
const provider = message.provider;
checkLoginStatus(websiteUrl, provider).then(loggedIn => {
sendResponse({ status: loggedIn });
});
}
return true; // Will respond asynchronously.
}
);