Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/cannot access a chrome url #63

Merged
merged 11 commits into from
Jul 27, 2023
41 changes: 8 additions & 33 deletions src/background/background.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,23 @@
import { IBytesRepository } from "../data/bytes/IBytesRepository";
import { addBytesTransferred } from "./backgroundHelpers";
import {
addBytesTransferred,
startRecordingBytesTransferred,
stopRecordingBytesTransferred,
} from "./backgroundHelpers";

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
juskek marked this conversation as resolved.
Show resolved Hide resolved
if (message === "getBytesTransferred") {
sendResponse(IBytesRepository.instance.getBytesTransferred());
}

const { tabId } = message;

if (message.command === "startRecordingBytesTransferred") {
IBytesRepository.instance.clearBytesTransferred();

chrome.debugger.attach({ tabId: tabId }, "1.2", () => {
chrome.debugger.sendCommand(
{ tabId: tabId },
"Network.enable",
{},
() => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
}
}
);
});

sendResponse(true);
startRecordingBytesTransferred(tabId, sendResponse);
}

if (message.command === "stopRecordingBytesTransferred") {
try {
await chrome.debugger.detach({ tabId: tabId });
} catch (e: unknown) {
if (
(e as Error).message ===
`Debugger is not attached to the tab with id: ${tabId}.`
) {
console.warn(
`Tried to detach debugger from tab (tabId: ${tabId}) when there was none attached. `
);
return;
}
throw e;
}
sendResponse(true);
stopRecordingBytesTransferred(tabId, sendResponse);
}
return true;
});
Expand Down
78 changes: 74 additions & 4 deletions src/background/backgroundHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { IBytesRepository } from "../data/bytes/IBytesRepository";

export const debuggingProtocolVersion = "1.2";
export const addBytesTransferred = async (bytes: number) => {
IBytesRepository.instance.addBytesTransferred(bytes);

Expand All @@ -10,16 +11,85 @@ export const addBytesTransferred = async (bytes: number) => {
IBytesRepository.instance.getBytesTransferred(),
},
});
} catch (e: unknown) {
} catch (error: unknown) {
if (
(e as Error).message ===
(error as Error).message ===
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
`Error Caught: ${e}\nIf popup is open and this error is seen in the console, debugging is required.`
`Error Caught: ${error}\nIf popup is open and this error is seen in the console, debugging is required.`
);
} else {
throw e;
throw error;
}
}
};

export type StartRecordingBytesTransferredReturnType = {
success: boolean;
message: string;
};

export const startRecordingBytesTransferred = async (
tabId: number,
sendResponse: (response: StartRecordingBytesTransferredReturnType) => void
): Promise<void> => {
IBytesRepository.instance.clearBytesTransferred();

chrome.tabs.get(tabId).then((tab) => {
if (tab.url && tab.url.startsWith("chrome://")) {
sendResponse({
success: false,
message:
"Cannot calculate emissions for a chrome:// URL, e.g. manage extensions page. Please try again on a valid webpage.",
});
return;
} else {
chrome.debugger
.attach({ tabId }, debuggingProtocolVersion)
.then(() => {
chrome.debugger.sendCommand(
{ tabId },
"Network.enable",
{},
() => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
}
sendResponse({
success: true,
message:
"Successfully started recording bytes transferred.",
});
return;
}
);
});
}
});
};

export const stopRecordingBytesTransferred = async (
tabId: number,
sendResponse: (response: boolean) => void
): Promise<void> => {
chrome.debugger
.detach({ tabId })
.then(() => {
sendResponse(true);
return;
})
.catch((error: unknown) => {
if (
(error as Error).message ===
`Debugger is not attached to the tab with id: ${tabId}.`
) {
console.warn(
`Tried to detach debugger from tab (tabId: ${tabId}) when there was none attached. `
);
sendResponse(false);
return;
}
throw error;
});
};
8 changes: 4 additions & 4 deletions src/utils/test-objects/mockChrome.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
export const mockTabId = 123;
export const mockChrome = {
tabs: {
query: jest.fn().mockImplementation((options, callback) => {
query: jest.fn().mockImplementation(async (options) => {
const tabs = [{ id: mockTabId }];
callback(tabs);
return tabs;
}),

reload: jest.fn().mockImplementation((tabId, options, callback) => {
callback();
reload: jest.fn().mockImplementation(async (tabId, options) => {
return;
}),
},
runtime: {
Expand Down
5 changes: 5 additions & 0 deletions src/view/popup/__tests__/usePopupRecordBytes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ describe("usePopup", () => {
expect(chrome.tabs.query).toHaveBeenCalledTimes(1);

expect(chrome.tabs.reload).toHaveBeenCalledTimes(1);

expect(chrome.runtime.sendMessage).toHaveBeenCalledTimes(2);
expect(chrome.runtime.sendMessage).toBeCalledWith(
"getBytesTransferred"
);
expect(chrome.runtime.sendMessage).toBeCalledWith({
command: "startRecordingBytesTransferred",
tabId: mockTabId,
Expand Down
10 changes: 6 additions & 4 deletions src/view/popup/popup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ export const Popup = () => {
{page === "landing" ? (
<LandingPage
onRecordButtonPress={async () => {
goToPage("recording");
await refreshAndGetSize();
if (await refreshAndGetSize()) {
juskek marked this conversation as resolved.
Show resolved Hide resolved
goToPage("recording");
}
}}
/>
) : page === "recording" ? (
Expand All @@ -69,8 +70,9 @@ export const Popup = () => {
) : page === "results" ? (
<ResultsPage
onRestartButtonPress={async () => {
goToPage("recording");
await refreshAndGetSize();
if (await refreshAndGetSize()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

goToPage("recording");
}
}}
recordings={calculationHistory}
selectedCountries={selectedCountries}
Expand Down
15 changes: 11 additions & 4 deletions src/view/popup/usePopup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const usePopup = () => {
return percentage;
};

const refreshAndGetSize = async () => {
const refreshAndGetSize = async (): Promise<boolean> => {
try {
sumPercentages();
setAverageSpecificEmissions(
Expand All @@ -78,18 +78,25 @@ export const usePopup = () => {
if (e instanceof Error) {
setError(e.message);
}
return;
return false;
}
try {
await calculationsRepository.setOngoingCalculation(true);
} catch (e: unknown) {
if (e instanceof Error) {
setError(e.message);
}
return;
return false;
}
try {
await refreshActiveTabAndRecordBytes(userType === "new user");
} catch (e: unknown) {
setError((e as Error).message);
juskek marked this conversation as resolved.
Show resolved Hide resolved
return false;
}
setError(undefined);
refreshActiveTabAndRecordBytes(userType === "new user");

return true;
};

const stopRecording = async (): Promise<void> => {
Expand Down
21 changes: 10 additions & 11 deletions src/view/popup/utils/backgroundStopRecordingBytes.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
export const backgroundStopRecordingBytes = () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs.length > 0) {
const tabId = tabs[0].id;
if (tabId) {
chrome.runtime.sendMessage({
command: "stopRecordingBytesTransferred",
tabId,
});
}
export const backgroundStopRecordingBytes = async () => {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs.length > 0) {
const activeTabId = tabs[0].id;
if (activeTabId) {
chrome.runtime.sendMessage({
command: "stopRecordingBytesTransferred",
activeTabId,
});
}
});
}
};
38 changes: 20 additions & 18 deletions src/view/popup/utils/refreshActiveTabAndRecordBytes.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
export const refreshActiveTabAndRecordBytes = async (bypassCache: boolean) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs.length > 0) {
const tabId = tabs[0].id;
if (tabId) {
chrome.tabs.reload(
tabId,
{
bypassCache: bypassCache,
},
() => {
chrome.runtime.sendMessage({
command: "startRecordingBytesTransferred",
tabId,
});
}
);
export const refreshActiveTabAndRecordBytes = async (
bypassCache: boolean
): Promise<void> => {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });

if (tabs.length > 0) {
const tabId = tabs[0].id;
if (tabId) {
await chrome.tabs.reload(tabId, {
bypassCache: bypassCache,
});

const { success, message } = await chrome.runtime.sendMessage({
command: "startRecordingBytesTransferred",
tabId,
});

if (!success) {
throw new Error(message);
}
}
});
}
};